(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 }

 

posted on 2015-04-17 14:39  海暗  阅读(1642)  评论(25编辑  收藏  举报