codeforces C1. The Great Julya Calendar 解题报告

      题目链接:http://codeforces.com/problemset/problem/331/C1

      这是第一次参加codeforces比赛(ABBYY Cup 3.0 - Finals (online version))成功AC的题目(n ≤ 106),解题的突破口是:Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero.

      用到了贪心思想,给出一个  0 ≤ n ≤ 106      的数,要想得到最少的减法次数,就要每次减去当前数中最大的位数。第一次提交时CE(没有包含头文件string.h),第二次和第三次的wa是因为自己太粗心了:对于n为0和除0外的个位数要加个特判。

 1 #include <iostream>
 2 #include <string.h>
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 using namespace std;
 6 
 7 int get_next(int x)
 8 {
 9     int a, n, i, j;
10     char s[20], t;
11     sprintf(s, "%d", x);   // 把整型的x转化为字符串
12     n = strlen(s);
13     for (i = 0; i < n; i++)    // 保证数组s按照从小到大的顺序排序
14     {
15         for (j = i+1; j < n; j++)
16         {
17             if (s[i] > s[j])
18             {
19                 t = s[i];
20                 s[i] = s[j];
21                 s[j] = t;
22             }
23         }
24     }
25     sscanf(s, "%d", &a);    // 把字符串转化成整型,以便函数返回
26     return (a % 10);          // 得到最大的位数
27 }
28 
29 int main()
30 {
31     int n, count, flag;
32     while (cin >> n)
33     {
34         flag = count = 0;
35         while (n >= 10)
36         {
37             n -= get_next(n);
38             count++;
39             flag = 1;
40         }
41         if (flag)
42             cout << count + 1 << endl;  // 加1是因为个位数到0的转化还需一次的count
43         else if (n == 0)    
44             cout << "0" << endl;
45         else                                                    // 除0以外的个位数
46             cout << "1" << endl; 
47     }
48     return 0;
49 }
原文地址:https://www.cnblogs.com/windysai/p/3198522.html