abcde a3 aaaaaa aa #
0 3
#include <queue> #include <cmath> #include <cstdio> #include <string> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define FIN freopen("input.txt","r",stdin) #define FOUT freopen("output.txt","w",stdout) #define UFOR(i,a,b) for(int i = a;i <= b;i++) #define CASE(T) int T;for(scanf("%d",&T);T--;) //typedef __int64 LL; //typedef long long LL; const double eps = 1e-10; const int maxn = 1000+5; char s[maxn],p[maxn]; int Next[maxn]; void getNext(const char x[],int len) { int i,j; j = Next[0] = -1; i = 0; while(i < len) { while(-1 != j && x[i] != x[j]) j = Next[j]; ++i,++j; if(x[i] == x[j]) Next[i] = Next[j]; else Next[i] = j; } } int KMP(const char p[],int plen,const char s[],int slen) { int i,j; int ans = 0; getNext(p,plen); i = j = 0; while(i < slen) { while(-1 != j && s[i] != p[j]) j = Next[j]; ++i,++j; if(j >= plen) { ans++; j = 0; } } return ans; } int main() { #ifndef ONLINE_JUDGE FIN; #endif // ONLINE_JUDGE while(~scanf("%s",s)) { if(s[0] == '#') break; scanf("%s",p); int ans = KMP(p,strlen(p),s,strlen(s)); printf("%d\n",ans); } return 0; }
asdf sdfg asdf ghjk
asdfg asdfghjk
给定字符串a,b,输出两个字符串连接起来的最小字典序,有个条件,如果字符串s1的某个前缀与s2的某个后缀相同,那么可以把前缀和后缀合并起来,也就是是要输出前缀或者后缀中的一个即可。
#include <cmath> #include <cstdio> #include <string> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define FIN freopen("input.txt","r",stdin) #define FOUT freopen("output.txt","w",stdout) #define CASE(T) int T;for(scanf("%d",&T);T--;) const int maxn = 100000+5; char a[maxn],b[maxn]; int Next[maxn]; void getNext(char x[],int m,int next[]) { int i,j; j = next[0] = -1, i = 0; while(i < m) { while(-1 != j && x[i] != x[j]) j = next[j]; ++i, ++j; if(x[i] == x[j]) next[i] = next[j]; else next[i] = j; } } int KMP(char s[],int slen,char p[],int plen) { int i,j,ans = 0; getNext(p,plen,Next); i = j = 0; while(i < slen) { while(-1 != j && s[i] != p[j]) j = Next[j]; ++i,++j; } return (j == -1) ? 0 : j; } int main() { #ifndef ONLINE_JUDGE FIN; #endif // ONLINE_JUDGE while(~scanf("%s %s",a,b)) { int lab = 0,lba = 0,t; int alen = strlen(a), blen = strlen(b); t = min(alen,blen); lab = KMP(a,alen,b,blen); lba = KMP(b,blen,a,alen); if(lab > lba) { a[alen-lab] = '\0'; printf("%s%s\n",a,b); } else if(lab < lba) { b[blen-lba] = '\0'; printf("%s%s\n",b,a); } else if(lab == 0) { string str1(a);str1 += b; string str2(b);str2 += a; printf("%s\n",min(str1,str2).c_str()); } else { char t1; t1 = a[alen-lab]; a[alen-lab] = '\0'; string str1(a); str1 += b; a[alen-lab] = t1; b[blen-lba] = '\0'; string str2(b); str2 += a; printf("%s\n",min(str1,str2).c_str()); } } return 0; }