HDU1296 Polynomial Problem
http://acm.hdu.edu.cn/showproblem.php?pid=1296
随手练习
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 int n; 5 char s[12345]; 6 ll Solve(string s,int i) 7 { 8 ll num=0; 9 int l=i-1; 10 int r=i+1; 11 string s1=""; 12 while(s[l]>='0'&&s[l]<='9') 13 { 14 s1+=s[l]; 15 l--; 16 } 17 reverse(s1.begin(),s1.end()); 18 ll ans=0; 19 ll sum=0; 20 int len=s1.length(); 21 for(int j=0; j<len; j++) 22 { 23 ans*=10; 24 ans+=(s1[j]-'0'); 25 } 26 if(ans==0){ 27 ans=1; 28 29 } 30 if(s[r]=='^') 31 { 32 r++; 33 while(s[r]>='0'&&s[r]<='9') 34 { 35 sum*=10; 36 sum+=(s[r]-'0'); 37 r++; 38 } 39 ll pos=n; 40 for(int j=1; j<sum; j++) 41 { 42 pos*=n; 43 } 44 num+=pos*ans; 45 } 46 else 47 { 48 num+=ans*n; 49 } 50 i=r; 51 if(s[l]=='-') 52 { 53 num*=-1; 54 } 55 return num; 56 } 57 int main() 58 { 59 while(~scanf("%d",&n)) 60 { 61 ll x=0; 62 scanf("%s",s); 63 int len=strlen(s); 64 if((s[0]>='0'&&s[0]<='9')||s[0]=='X') 65 { 66 string s1=""; 67 int i=0; 68 int pos=0; 69 int flag=0; 70 for(i=0; s[i]!='+'&&s[i]!='-'&&i<len; i++) 71 { 72 s1+=s[i]; 73 if(s[i]=='X') 74 { 75 flag=1; 76 pos=i; 77 } 78 } 79 if(flag) 80 { 81 x+=Solve(s1,pos); 82 flag=0; 83 } 84 else 85 { 86 ll ans=0; 87 for(int j=0; j<s1.length(); j++) 88 { 89 ans*=10; 90 ans+=(s1[j]-'0'); 91 } 92 x+=ans; 93 } 94 for(int j=i; j<len;) 95 { 96 if(s[j]=='-'||s[j]=='+') 97 { 98 string s2=""; 99 s2+=s[j]; 100 j++; 101 int ans=0; 102 while(s[j]!='-'&&s[j]!='+'&&j<len) 103 { 104 s2+=s[j]; 105 ans++; 106 if(s[j]=='X') 107 { 108 pos=ans; 109 flag=1; 110 } 111 //cout<<s[j]<<endl; 112 j++; 113 } 114 if(flag) 115 { 116 x+=Solve(s2,pos); 117 flag=0; 118 } 119 else 120 { 121 ll ans=0; 122 for(int j=1; j<s2.length(); j++) 123 { 124 ans*=10; 125 ans+=(s2[j]-'0'); 126 } 127 if(s2[0]=='-') 128 { 129 ans*=-1; 130 } 131 x+=ans; 132 } 133 flag=0; 134 } 135 } 136 cout<<x<<endl; 137 } 138 else 139 { 140 int flag=0; 141 int pos=0; 142 string s3=""; 143 s3+=s[0]; 144 int i; 145 for(i=1; s[i]!='-'&&s[i]!='+'&&i<len; i++) 146 { 147 s3+=s[i]; 148 if(s[i]=='X') 149 { 150 flag=1; 151 pos=i; 152 } 153 } 154 if(flag) 155 { 156 x+=Solve(s3,pos); 157 flag=0; 158 } 159 else 160 { 161 ll ans=0; 162 for(int j=1; j<s3.length(); j++) 163 { 164 ans*=10; 165 ans+=(s3[j]-'0'); 166 } 167 if(s3[0]=='-') 168 { 169 ans*=-1; 170 } 171 x+=ans; 172 } 173 flag=0; 174 for(int j=i; j<len;) 175 { 176 if(s[j]=='-'||s[j]=='+') 177 { 178 string s2=""; 179 s2+=s[j]; 180 j++; 181 int ans=0; 182 while(s[j]!='-'&&s[j]!='+'&&j<len) 183 { 184 s2+=s[j]; 185 ans++; 186 if(s[j]=='X') 187 { 188 pos=ans; 189 flag=1; 190 } 191 //cout<<s[j]<<endl; 192 j++; 193 } 194 if(flag) 195 { 196 x+=Solve(s2,pos); 197 flag=0; 198 } 199 else 200 { 201 ll ans=0; 202 for(int j=1; j<s2.length(); j++) 203 { 204 ans*=10; 205 ans+=(s2[j]-'0'); 206 } 207 if(s2[0]=='-') 208 { 209 ans*=-1; 210 } 211 x+=ans; 212 } 213 flag=0; 214 } 215 } 216 cout<<x<<endl; 217 } 218 } 219 return 0; 220 }