ZOJ 3336 Friend Number II

题目大意:

给你一个正整数x,要求每个数字上的总和和x相同且比x大的最小整数。

如x=12 答案为21  x=10 答案为100

 

思路:

因为要比x大的最小,我们很自然的想到个位-1十位+1不就可以了。但是要注意如果是0的话,0-1变为9那么是不行的!而9+1的话变为0也是不行的。

最个位开始查找,找第一个不为0的数-1(不为0的下标为not_zero),在not_zero往高位找到第一个不为9的个数+1,(这样保证了比x大)然后在9+1的这里往后排个序保证最小。

为什么要排序?如x=520那么按照上面的就会变为610 而答案应该为601

 

  1. #include<cstdio>  
  2. #include<cstring>  
  3. #include<algorithm>  
  4. using namespace std;  
  5. const int MAXN=1024;  
  6. char s[MAXN];  
  7. int main()  
  8. {  
  9.     int T;  
  10.     scanf("%d",&T);  
  11.     while(T--)  
  12.     {  
  13.         s[0]='0';  
  14.         scanf("%s",s+1);  
  15.         int len=strlen(s);  
  16.         int not_zero=len-1;  
  17.         while(s[not_zero]=='0')   
  18.             not_zero--;  
  19.         s[not_zero]--;  
  20.           
  21.         int not_nine=not_zero-1;  
  22.         while(s[not_nine]=='9')  
  23.             not_nine--;  
  24.         s[not_nine]++;  
  25.   
  26.         sort(s+not_nine+1,s+len);  
  27.           
  28.         if(s[0]=='0')  
  29.             printf("%s\n",s+1);  
  30.         else  
  31.             printf("%s\n",s);  
  32.   
  33.     }  
  34.     return 0;  
  35. }  
posted @ 2014-01-08 16:24  刘俊鹏123  阅读(179)  评论(0编辑  收藏  举报
重生之大文豪