您的位置:首页 > 其它

SRM 604 DIV2 250

2014-01-12 14:01 344 查看
题意:给你一个字符串向量,问你有中间多少个串循环相等(循环相等的意思就是 “ab”,“ba”,经过移位以后还相等的字符串)

解题思路:KMP,这种字符串有一个性质,就是 如果 a的长度等于b的长度,且 能在 a+a 中匹配到b,则可以断定这两个字符串循环相等

解题代码:

#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <fstream>
#include <numeric>
#include <iomanip>
#include <bitset>
#include <list>
#include <stdexcept>
#include <functional>
#include <utility>
#include <ctime>
using namespace std;

#define PB push_back
#define MP make_pair

#define REP(i,n) for(i=0;i<(n);++i)
#define FOR(i,l,h) for(i=(l);i<=(h);++i)
#define FORD(i,h,l) for(i=(h);i>=(l);--i)

typedef vector<int> VI;
typedef vector<string> VS;
typedef vector<double> VD;
typedef long long LL;
typedef pair<int,int> PII;

int kmp(string a, string b)
{
int pi[100];
int m = b.size();
memset(pi,0,sizeof(pi));
pi[0] = -1;
int k = -1 ;
for(int i = 1 ;i < m ; i ++)
{
while(k >= 0 && b[k+1] != b[i])
k = pi[k];
if(b[k+1] == b[i])
k = k +1;
pi[i] = k;
}
int n = a.size();
int q = -1 ;
for(int i = 0;i < n;i ++)
{
while(q >= 0 && b[q+1] != a[i])
q = pi[q];
if(b[q+1] == a[i])
q = q +1;
if(q == m -1)
{
return 1;
}
}
return 0 ;

}
class FoxAndWord
{
public:
int howManyPairs(vector <string> words)
{

int k = words.size();
int sum = 0 ;
for(int i = 0;i < k ;i ++)
for(int j = i + 1;j < k; j ++)
{
string temp = words[i] + words[i];
if(kmp(temp,words[j])&& words[i].size() == words[j].size())
{          sum ++ ;

}
}

return sum ;

}
};


代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: