给定n个字符串s[1...n], 求有多少个数对(i, j), 满足i < j 且 s[i] + s[j] == s[j] + s[i]?

题目

思路:

对于字符串a,b, (a.size() < b.size()), 考虑对字符串b满足什么条件:

由1、3可知a是b的前后缀,由2知b有一个周期是3,即a.size(),所以b是用多个a拼接而成的,有因为a是b的前后缀,所以a和b的循环节相同,且a,b均恰好由整数个循环节组成。循环节长度 = 字符串长度 - 最大公共前后缀长度。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 1e6 + 5;
string s[maxn];
int nxt[maxn];
map<string, int> mp;
void getnext(string s){
	int j = -1;
	nxt[0] = -1;
	int n = s.size();
	s = ' ' + s;
	for(int i = 1; i <= n; i++){
		while(j >= 0 && s[i] != s[j + 1]){
			j = nxt[j];
		}
		nxt[i] = j + 1;
		j++;
	}
}
// void f(vector<int> &a){
//     a.push_back(6);
// }
signed main(){
    int n;
    while(cin >> n){
//         cin >> n;
        mp.clear();
        int res = 0;
        for(int i = 1; i <= n; i++){
            cin >> s[i];
            getnext(s[i]);
            int m = s[i].size();
            int T = m - nxt[m];
            if(m % T != 0){
                T = m;//整个字符串也是一个循环节
            }
            string t = s[i].substr(0, T);
            res += mp[t];
            mp[t]++;
        }
         cout << res << '\n';
    }
    
//     string s = "666";
//     cout << s.size() << '\n';
//     getnext(s);
//     cout << s.size() << '\n';
//     vector<int> a;
//     cout << a.size() << '\n';
//     f(a);
//     cout << a.size() << '\n';
    return 0;
}
相关推荐
你撅嘴真丑2 小时前
第九章-数字三角形
算法
uesowys2 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder2 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮2 小时前
AI 视觉连载1:像素
算法
智驱力人工智能3 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥4 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风4 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風4 小时前
8.1 PFH&&FPFH
图像处理·算法
NEXT064 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法
代码游侠5 小时前
学习笔记——设备树基础
linux·运维·开发语言·单片机·算法