(ps:該的代碼在30行的時候,會出現負數。也就是有問題。優化見下方)
O(n^3)
可以進一步優化為O(n^2)->通過優化cal函數
1 #include <iostream> 2 #include <string> 3 #include <stdio.h> 4 #include <memory> 5 #include <string.h> 6 using namespace std; 7 long long map[1001][1001]; 8 string input; 9 void cal(int start ,int end) 10 { 11 if(start==end) 12 { 13 map[start][end]=1; 14 return ; 15 } 16 if(end-start==1) 17 { 18 if(input[start]==input[end]) 19 map[start][end]=3; 20 else 21 map[start][end]=2; 22 return ; 23 } 24 map[start][end]+=map[start][end-1]+1; 25 for(int i=end-1;i>=start;i--) 26 { 27 if(input[i]==input[end]) 28 map[start][end]+=map[i+1][end-1]+1; 29 } 30 map[start][end]%=100007; 31 } 32 int main() 33 { 34 int T; 35 int Case=0; 36 cin>>T; 37 38 while(T--) 39 { 40 Case++; 41 memset(map,0,sizeof(map)); 42 43 cin>>input; 44 for(int i=0;i<input.size();i++) 45 { 46 for(int j=i;j>=0;j--) 47 { 48 cal(j,i); 49 } 50 } 51 cout<<"Case #"<<Case<<": "<<map[0][input.size()-1]<<endl; 52 } 53 54 }
瀟湘緣說的很對,以上代碼是O(n^3)的,在面對最大數據1000的時候基本就是超時了的:
以下是更正代碼:優化了cal()函數,把map[start+1][end]充分利用起來,是O(n^2)的時間開銷了
(ps:為什么耗時還是19ms。。)
(ps:之前的代碼因為少了37行的過程,輸出會有負數,也就是有問題。)
以下代碼已通過大數據測試
1 #include <iostream> 2 #include <string> 3 #include <stdio.h> 4 #include <memory> 5 #include <string.h> 6 using namespace std; 7 long long map[1001][1001]; 8 string input; 9 10 11 12 int main() 13 { 14 int T; 15 int Case=0; 16 cin>>T; 17 18 while(T--) 19 { 20 Case++; 21 memset(map,0,sizeof(map)); 22 cin>>input; 23 for(int i=0;i<input.size();i++) 24 { 25 for(int j=i;j>=0;j--) 26 { 27 if(j==i) 28 { 29 map[j][i]=1; 30 continue; 31 } 32 map[j][i]=map[j+1][i]-map[j+1][i-1]+map[j][i-1]; 33 if(input[j]==input[i]) 34 { 35 map[j][i]+= map[j+1][i-1]+1; 36 } 37 map[j][i]=(map[j][i]+100007)%100007; 38 } 39 } 40 cout<<"Case #"<<Case<<": "<<map[0][input.size()-1]<<endl; 41 } 42 43 }