UVa 263 Number Chains

 1  #include <stdio.h>
 2  #include <stdlib.h>
 3  #include <algorithm>
 4  #include <iostream>
 5  #include <string.h>
 6  #include <string>
 7  #include <set>
 8  using namespace std;
 9  int main()
10  {
11      string str;
12      while(cin>>str && str[0]!='0')
13      {
14          int start=atoi(str.c_str());
15          set<int> ss;
16          int coun=0;
17          printf("Original number was %s\n",str.c_str());
18          int ans=0,pre=-10000000,c=0;
19          while(1)
20          {
21              string second=str;
22              sort(second.begin(),second.end());
23              string first=second;
24              reverse(first.begin(),first.end());
25              int f=atoi(first.c_str()),s=atoi(second.c_str());
26              ans=f-s;
27              printf("%d - %d = %d\n",f,s,ans);
28              c++;
29              ss.insert(ans);
30              if(coun==ss.size()) break;
31              coun=ss.size();
32              if(ans==pre) break;
33              pre=ans;
34              char tmp[15];
35              sprintf(tmp,"%d",ans);
36              str=tmp;
37          }
38          printf("Chain length %d\n\n",c);
39      }
40      return 0;

41  }

留言

這個網誌中的熱門文章

Things a Little Bird Told Me: Confessions of the Creative Mind

UVa 12970 Alcoholic Pilots

UVa 483 Word Scramble