1. 程式人生 > >5920- Ugly Problem (字串模擬&&思路)

5920- Ugly Problem (字串模擬&&思路)

Everyone hates ugly problems.  You are given a positive integer. You must represent that number by sum of palindromic numbers.  A palindromic number is a positive integer such that if you write out that integer as a string in decimal without leading zeros, the string is an palindrome. For example, 1 is a palindromic number and 10 is not.

Input

In the first line of input, there is an integer T denoting the number of test cases. For each test case, there is only one line describing the given integer s (1≤s≤101000).

Output

For each test case, output “Case #x:” on the first line where x is the number of that test case starting from 1. Then output the number of palindromic numbers you used, n, on one line. n must be no more than 50. en output n lines, each containing one of your palindromic numbers. Their sum must be exactly s.

Sample Input

2
18
1000000000000

Sample Output

Case #1:
2
9
9
Case #2:
2
999999999999
1

題意:

給出個炒雞大的數,把他用50個以內的迴文數之和表示。

思路:

//思路:設a為給的數
while(a>=10)
{
    x=a;//取前一半
    x--;
    x+= reverse(x);
    a=a-x;
}

Solution:

#include <bits/stdc++.h>
using namespace std;
const int  maxn = 1e3+10;
bool getPal(char *s)//
{
    int n=strlen(s);
    if(n==1) return 1;
    if(n==2&&s[0]=='1')
    {
        s[0]='9';
        s[1]=0;
        return 0;
    }
    s[(n+1)/2-1]--;
    for(int i=(n+1)/2-1; i>0; i--) //減一可能會有小於零的情況,模擬減法
    {
        if(s[i]<'0')
            s[i]+=10,s[i-1]--;
    }
    if(s[0]=='0')               //如果首位減沒了,那麼全部進一位,這是總的位數少1
    {
        for(int i=0; i<n; i++)
        {
            s[i]=s[i+1];
        }
        n--;
    }
    for(int i=(n+1)/2; i<n; i++)
        s[i]=s[n-i-1];
    return 0;
}
bool subStr(char *a,char *b)//算a-b,結果存入a  其實就是從s中減去構造的迴文串
{
    int na = strlen(a);
    int nb = strlen(b);
    for(int i=na-1,j=nb-1; j>=0; i--,j--)
    {
        if(a[i]>=b[j]) a[i] = a[i]-b[j]+'0';
        else
            a[i]=a[i]+10-b[j]+'0',a[i-1]--;
    }
    int p;
    for(p=0; a[p]=='0'; p++)
    {
        if(p==na)
            return 1; //剛好減完,說明相等
    }
    for(int i=0; p<=na; i++,p++)
        a[i]=a[p];
    return 0;
}
char s[maxn],ans[50][maxn];
int cnt;
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    for(int cas=1; cas<=t; cas++)
    {
        cin>>s;
        for(cnt=0;; cnt++)
        {
            strcpy(ans[cnt],s);
            if(getPal(ans[cnt])||subStr(s,ans[cnt]))
                break;
        }
        printf("Case #%d:\n%d\n",cas,cnt+1);
        for(int i=0; i<=cnt; i++)
        {
            printf("%s\n",ans[i]);
        }
    }
    return 0;

}