51nod 2020 排序相減

題目鏈接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=2020
“排序相減”操作是指對於任意一個四位數n,將四個數字分別進行順序排序和逆序排序,得到兩個數取相減後結果的絕對值n1,然後繼續將n1中的四個數字進行順序排序和逆序排序,得到兩個數取相減後結果的絕對值n2,以此類推,最後總會得到一個數字黑洞,無法跳出。

例如:樣例2中4176 = 6532 - 2356

Input

第一行輸入一個整數T,表示數據組數(1<T<10000);
第二行輸入一個正整數n(1000<=n<=9999)和一個正整數k(1<=k<=100),表示操作次數;

Output

對於每組數據,輸出對於開始的數據n在第k次“排序相減”後結果絕對值。

Input示例

2
1234 2
3562 1

Output示例

8352
4176

AC代碼:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
    return a>b;
}
int fun(int s)//對這個數排序相減 
{
    int i,a[5],b[5];
    int num,m,n;
    num=s;
    i=0;
    while(num)
    {
        a[i]=b[i]=num%10;
        num/=10;
        i++;
    }
    sort(a,a+4);
    sort(b,b+4,cmp);
    m=a[0]*1000+a[1]*100+a[2]*10+a[3];
    n=b[0]*1000+b[1]*100+b[2]*10+b[3];
    return n-m;
}
int main()
{
    int t,n,num;
    cin>>t;
    while(t--)
    {
        cin>>num>>n;
        int x;
        x=num;
        while(n--)
        {
            x=fun(x);
        }
        cout<<x<<endl;
    }
return 0;
} 
發佈了105 篇原創文章 · 獲贊 26 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章