在写 Oulipo POJ - 3461 时候遇上的奇怪的问题
在格式输入上不一样,提交的时候返回TLE,两段代码如下:
A#include<iostream>
#include<cstdio> #include<cstring> using namespace std; #define MAXN 1000100 int next[MAXN],pLen,sLen; char p[MAXN],s[MAXN]; //优化过后的next 数组求法 void GetNextval() { next[0] = -1; int k = -1; int j = 0; while (j < pLen) { //p[k]表示前缀,p[j]表示后缀 if (k == -1 || p[j] == p[k]) { ++j; ++k; if (p[j] != p[k]) next[j] = k; //之前只有这一行 else next[j] = next[k]; } else { k = next[k]; } } } int KmpSearch() { int i = 0; int j = 0; int ans = 0; while (i !=sLen && j != pLen) { //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++ if (j == -1 || s[i] == p[j]) { i++; j++; } else { j = next[j]; } if(j == pLen) { ans++; j = next[j]; } } return ans; } int main(){ int t,ans; scanf("%d",&t); while(t--) { scanf("%s%s", p, s); sLen = strlen(s); pLen = strlen(p);
GetNextval() ans = KmpSearch(); cout<<ans<<endl; } return 0; }
TLE:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 #define MAXN 1000100 6 7 int next[MAXN],pLen,sLen; 8 char p[MAXN],s[MAXN]; 9 10 //优化过后的next 数组求法 11 void GetNextval() 12 { 13 14 next[0] = -1; 15 int k = -1; 16 int j = 0; 17 while (j < pLen) 18 { 19 //p[k]表示前缀,p[j]表示后缀 20 if (k == -1 || p[j] == p[k]) 21 { 22 ++j; 23 ++k; 24 25 if (p[j] != p[k]) 26 next[j] = k; //之前只有这一行 27 else 28 next[j] = next[k]; 29 } 30 else 31 { 32 k = next[k]; 33 } 34 } 35 } 36 37 int KmpSearch() 38 { 39 int i = 0; 40 int j = 0; 41 int ans = 0; 42 43 44 while (i !=sLen && j != pLen) 45 { 46 //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++ 47 if (j == -1 || s[i] == p[j]) 48 { 49 i++; 50 j++; 51 } 52 else 53 { 54 55 j = next[j]; 56 } 57 58 if(j == pLen) { 59 ans++; 60 j = next[j]; 61 } 62 63 } 64 65 return ans; 66 } 67 int main(){ 68 int t,ans; 69 scanf("%d",&t); 70 while(t--) { 71 cin>>p; 72 cin>>s; 73 sLen = strlen(s); 74 pLen = strlen(p); 75 GetNextval(); 76 ans = KmpSearch(); 77 cout<<ans<<endl; 78 } 79 80 81 82 return 0; 83 }