问题 E: Shortest Distance (20)

问题 E: Shortest Distance (20)

 1 #include <iostream>
 2 #include<cstring>
 3 #include<vector>
 4 #define maxn 100001
 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 6 using namespace std; 
 7 int n;
 8 typedef struct Dnode{
 9     int s;
10     int e;
11     int d;
12 }Dnode;
13 
14 Dnode Dset[maxn];
15 int p1,p2;
16 void solve(){
17     int sum1=0;
18     int min;
19     int s=p1;
20     int e=p2;
21     while(s!=e){
22         sum1+=Dset[s].d;
23         s=Dset[s].e;
24     }
25     min=sum1;
26     sum1=0;
27     
28     while(s!=p1){
29         sum1+=Dset[s].d;
30         s=Dset[s].e;
31     }
32     if(min<sum1) cout<<min<<endl;
33     else  cout<<sum1<<endl;
34     
35 }
36 int main(int argc, char** argv) {
37     int n;
38     int i;
39     int d;
40     int t;
41     int j;
42     int test;
43     Dnode pa; 
44     while(cin>>n){
45         t=1;
46         for(i=1;i<=n;i++){
47             cin>>d;
48             j=i+1;
49             if(j>n) j%=n;
50             Dset[t].s=i;
51             Dset[t].e=j;
52             Dset[t].d=d;
53             t++;
54         }
55         
56         cin>>test;
57         while(test--){
58             cin>>p1>>p2;
59             solve();
60         }
61         
62     }
63     return 0;
64 }

时间超时代码

优化一下,还超时:

代码如下:

 1 #include <iostream>
 2 #include<cstring>
 3 #include<vector>
 4 #define maxn 100001
 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 6 using namespace std; 
 7 int n;
 8 typedef struct Dnode{
 9     int s;
10     int e;
11     int d;
12 }Dnode;
13 
14 Dnode Dset[maxn];
15 int p1,p2;
16 int total_d;
17 void solve(){
18     int sum1=0;
19     int min;
20     int s=p1;
21     int e=p2;
22     while(s!=e){
23         sum1+=Dset[s].d;
24         s=Dset[s].e;
25     }
26     min=sum1;
27     sum1=total_d-min;
28     if(min<sum1) cout<<min<<endl;
29     else  cout<<sum1<<endl;
30     
31 }
32 int main(int argc, char** argv) {
33     int n;
34     int i;
35     int d;
36     int t;
37     int j;
38     int test;
39     Dnode pa; 
40     while(cin>>n){
41         t=1;
42         total_d=0;
43         for(i=1;i<=n;i++){
44             cin>>d;
45             total_d+=d;
46             j=i+1;
47             if(j>n) j%=n;
48             Dset[t].s=i;
49             Dset[t].e=j;
50             Dset[t].d=d;
51             t++;
52         }
53         
54         cin>>test;
55         while(test--){
56             cin>>p1>>p2;
57             solve();
58         }
59         
60     }
61     return 0;
62 }

暂时还没想到哪可以优化,不过我估摸着,得预先把每个点的最小值弄出来,因为M最大为10^4,而N最大为10^6 M*N=10^10 严重超时!

如果我能预先把它算出来的话最大的复杂度为O(10^4)

猜你喜欢

转载自www.cnblogs.com/industrial-fd-2019/p/10623546.html