ZOJ

Given a positive integer x, let S(x) denotes the sum of all x's digits. Two integers x and y are friend numbers if S(x)=S(y). Here comes the problem: Given a positive integer x, of course it has a lot of friend numbers, find the smallest one which is greater than x,please.


Input

There are multiple test cases. The first line of input is an integer T (0<T<230) indicating the number of test cases. Then T test cases follow. Each case is an integer x (0<x<=101000).


Output
For each test case, output the result integer in a single line.

Sample Input
3
12
19
222

Sample Output
21
28
231

Note: No input data start with digit 0 and you should not output a number starts with 0.


题意:给出一个数n求出最小数m:大于n的数并且m和n的每一位数的和相等。


思路:贪心,从最后一个不是零的数减一,它的前一位数加一。当加一的时候遇到九就要把九保留下来,往前继续找可以加一的数,找的之后把后面的数排序。

#include<stack>
#include<queue>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<map>
#include<algorithm>
#define maxn 100005
#define MAXN 10000
#define MAXM 10005
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
string s;
int a[maxn];
int main(){
    int t;scanf("%d",&t);
    while(t--){
        cin>>s;
        mem(a,0);
        int n=s.size();
        for(int i=0;i<n;i++){
            a[i+1]=s[i]-'0';
        }
        int x=-1;
        for(int i=n;i>=1;i--){
            if(a[i]!=0){x=i;break;}
        }
            a[x]-=1;
            int y=x-1;
            while(a[y]+1>=10&&y>=0){y--;}
            a[y]+=1;
            sort(a+y+1,a+n+1);
        if(a[0]!=0)printf("%d",a[0]);
        for(int i=1;i<=n;i++){
            printf("%d",a[i]);
        }printf("
");
    }
}




原文地址:https://www.cnblogs.com/da-mei/p/9053239.html