UVa-10317 - Equating Equations
一个即将高一的网友问的我的题。汗,我怎么大一才接触编程!
用STL写的,当时UVa挂了,没有去测试。之后发现TLE了,把vector改成数组依然如此。一时没想到怎么解决,先这样吧,以后再看看。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<sstream> 6 using namespace std; 7 const int maxx=20; 8 int main() 9 { 10 //freopen("in.txt","r",stdin); 11 //freopen("out.txt","w",stdout); 12 string s; 13 while(getline(cin,s)) 14 { 15 stringstream ss(s); 16 int v1[maxx]={}; 17 char v2[maxx]={}; 18 int p1=0,p2=0; 19 bool flag=0; 20 int sum=0; 21 while(1) 22 { 23 flag=!flag; 24 if(flag) 25 { 26 int t; 27 ss>>t; 28 if(ss.fail()) break; 29 v1[p1++]=t; 30 sum+=t; 31 } 32 else 33 { 34 char t; 35 ss>>t; 36 if(ss.fail()) break; 37 v2[p2++]=t; 38 } 39 } 40 while(1) 41 { 42 int num=0; 43 bool f1=0,f2=0; 44 int i=0,j=0; 45 num+=v1[i++]; 46 for(;i<p1;i++,j++) 47 { 48 if(v2[j]=='+') f2=0; 49 else f2=1; 50 if(v2[j]=='=') 51 { 52 f1=1; 53 f2=0; 54 } 55 if(f1) f2=!f2; 56 if(!f2) num+=v1[i]; 57 else num-=v1[i]; 58 } 59 if(num==0) 60 { 61 i=0; 62 j=0; 63 printf("%d",v1[i++]); 64 for(;i<p1;i++,j++) 65 printf(" %c %d",v2[j],v1[i]); 66 break; 67 } 68 else 69 { 70 if(!next_permutation(v1,v1+p1)) 71 { 72 printf("no solution"); 73 break; 74 } 75 } 76 } 77 printf("\n"); 78 } 79 }