先上题目:
Oaiei is a good boy who loves math very much, he would like to simplify some mathematical expression, can you help him? For the sake of simplicity, the form of expression he wanted to simplify is shown as follows:
Given the expression S, the length of S is less than 200, there is no space in the given string.
Output the simplest expression S’, you should output S’ accordance to the X with descending order of power. Note that X^1 need only output X, 1X need only output X.
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #define MAX 1002 5 #define max(x,y) (x > y ? x : y) 6 using namespace std; 7 8 int c[MAX]; 9 char s[MAX]; 10 int maxn; 11 12 typedef struct{ 13 bool isx; 14 bool isnum; 15 bool ise; 16 int r; 17 int num; 18 int e; 19 }word; 20 21 word w[MAX]; 22 int tot; 23 24 25 void deal(){ 26 int num,e; 27 if(w[tot].isnum==0 && w[tot].isx==0){return ;} 28 else if(w[tot].isnum==0 && w[tot].isx==1) 29 { 30 num=1; 31 if(w[tot].ise!=0) e=w[tot].e; 32 else e=1; 33 } 34 else if(w[tot].isnum==1 && w[tot].isx==0){num=w[tot].num;e=0;} 35 else if(w[tot].isnum==1 && w[tot].isx==1) 36 { 37 num=w[tot].num; 38 if(w[tot].ise!=0) e=w[tot].e; 39 else e=1; 40 } 41 c[e]+=w[tot].r*num; 42 maxn=max(e,maxn); 43 } 44 45 int main() 46 { 47 int l; 48 char o; 49 //freopen("data.txt","r",stdin); 50 while(scanf("%s",s)!=EOF){ 51 getchar(); 52 maxn=0; 53 memset(c,0,sizeof(c)); 54 memset(w,0,sizeof(w)); 55 tot=0; 56 l=strlen(s); 57 w[tot].r=1; 58 for(int i= (s[0]==‘+‘ ? 1 : 0);i<l;i++){ 59 o=s[i]; 60 if(o==‘X‘) {w[tot].isx=1;} 61 else if(o==‘+‘){ 62 deal(); 63 tot++; 64 w[tot].r=1; 65 continue; 66 } 67 else if(o==‘-‘){ 68 deal(); 69 tot++; 70 w[tot].r=-1; 71 continue; 72 } 73 74 if(‘0‘<=o && o<=‘9‘ && w[tot].isx==0){ 75 w[tot].num=w[tot].num*10+(o-‘0‘); 76 w[tot].isnum=1; 77 }else if(w[tot].isx!=0 && (o>=‘0‘ && o<=‘9‘)){ 78 w[tot].e=w[tot].e*10+(o-‘0‘); 79 w[tot].isx=1; 80 w[tot].ise=1; 81 } 82 } 83 84 deal(); 85 int count=0; 86 87 for(int i=maxn;i>1;i--){ 88 if(c[i]==0) continue; 89 if(count && c[i]>0) printf("+"); 90 if(c[i]!=1 && c[i]!=-1) printf("%dX^%d",c[i],i); 91 else{ 92 if(c[i]==-1) printf("-"); 93 printf("X^%d",i); 94 } 95 count++; 96 } 97 if(count && c[1]>0) { 98 printf("+"); 99 count++; 100 } 101 if(c[1]!=0){ 102 if(c[1]!=1 && c[1]!=-1) printf("%d",c[1]); 103 if(c[1]==-1) printf("-"); 104 printf("X"); 105 count++; 106 } 107 if(count && c[0]>0) printf("+"); 108 if((count>0 && c[0]!=0) || count==0) printf("%d",c[0]); 109 printf("\n"); 110 } 111 return 0; 112 }
FZU - 1606 - Format the expression
原文:http://www.cnblogs.com/sineatos/p/3565034.html