有一道数学之美ACM题WA,自己各种测试实例都通过 ,求解
程序代码:
//数字之美: #include <stdio.h> #include <memory.h> #include <string.h> int main(void) { char s0[100005]; char s1[100005]; char s2[100005]; int num4,num7,numall,halfnumall; int i,len,j; while(scanf("%s",s0)!=EOF) { memset(s1,0,sizeof(char)*100005); memset(s2,0,sizeof(char)*100005); //1.找到最小幸运数字: len=strlen(s0); //s0=44447777,44474777,....44477774 //s2=11112222,11121222,....11122221 //s0=444888,4548,12345678,88 //s2=111333,1213,11112223,33 for(i=len-1; i>=0; i--) { if(s0[i]<='4') { s2[i+1]=1; } else if(s0[i]<='7') { s2[i+1]=2; } else { s2[i+1]=3; } } //s2=111333,1213,11112223,33 //s2=112111,1221,11121111,111 for(i=len; i>0; i--) { if(s2[i]>=3) { s2[i-1]++; s2[i]=1; for(j=len; j>i; j--) { s2[j]=1; } } } //s1=447444,4774,44474444,444 if(s2[0]==0) { for(i=1; i<=len+3; i++) { switch(s2[i]) { case 1: s1[i-1]=4; break; case 2: s1[i-1]=7; break; } } } else { for(i=0; i<=len+3; i++) { switch(s2[i]) { case 1: s1[i]=4; break; case 2: s1[i]=7; break; } } } //2.将最小幸运数字变为超级幸运数字: //2.1统计4,7个数: for(i=0,num4=0,num7=0; i<=len+3; i++) { if(s1[i]==4) { num4++; } else if(s1[i]==7) { num7++; } } numall=num4+num7; //2.2 若为奇数: if(numall%2) { numall++; halfnumall=numall/2; for(i=0; i<halfnumall; i++) { s1[i]=4; } for(i=0; i<halfnumall; i++) { s1[halfnumall+i]=7; } goto out; } //2.2 若为偶数: while(num7>num4) { for(i=numall+3; i>=0; i--) { if(s1[i]==4) { s1[i]=7; for(i++; i<=numall+3; i++) { if(s1[i]==7) { s1[i]=4; } } break; } } //统计4,7个数 for(i=0,num4=0,num7=0; i<=numall+3; i++) { if(s1[i]==4) { num4++; } else if(s1[i]==7) { num7++; } } if(num4==0)//全都是7的话: { numall+=2; halfnumall=numall/2; for(i=0; i<halfnumall; i++) { s1[i]=4; } for(i=0; i<halfnumall; i++) { s1[halfnumall+i]=7; } goto out; } } for(i=numall+3; i>=0&&num4>num7; i--) { if(s1[i]==4) { s1[i]=7; num4--; num7++; } } out: for(i=0;; i++) { if(s1[i]==4) { printf("4"); } else if(s1[i]==7) { printf("7"); } else { break; } } printf("\n"); } return 0; }