POJ1016 Numbers That Count
题目来源:http://poj.org/problem?id=1016
题目大意:
对一个非负整数定义一种运算(inventory):数这个数中各个数字出现的次数,然后按顺序记录下来。比如“5553141”有2个1,1个3,一个4,3个5,于是运算后为“21131435”,对于这种运算有的数字有着有趣的性质:如“31123314”,它运算后的结果和它本身是一样的(self-inventorying)。如果做j次inventory运算后,第j次迭代的结果是self-inventorying的,则称这个数是j步后self-inventory.此外,如果n进行j次迭代后,再进行k(k>=2)次迭代,结果与第j次迭代的结果相等,称它 enters an inventory loop of length k.
写一个程序,判断一系列非负整数属于上面三种数字的哪一种(只考虑15次迭代)。
输入:一系列的非负整数,每个最多80位,-1标志结束。
输出:对于每一个输入的整数n,根据该数的性质输出一下四条语句中的一条:
n is self-inventorying
n is self-inventorying after j steps
n enters an inventory loop of length k
n can not be classified after 15 iterations
Sample Input
22 31123314 314213241519 21221314 111222234459 -1
Sample Output
22 is self-inventorying 31123314 is self-inventorying 314213241519 enters an inventory loop of length 2 21221314 is self-inventorying after 2 steps 111222234459 enters an inventory loop of length 2
这道题我就是用简单的模拟做的,具体实现见代码。
1 ////////////////////////////////////////////////////////////////////////// 2 // POJ1016 Numbers That Count 3 // Memory: 272K Time: 47MS 4 // Language: C++ Result: Accepted 5 ////////////////////////////////////////////////////////////////////////// 6 7 #include <iostream> 8 #include <string> 9 10 using namespace std; 11 12 string int2str(int n) { 13 string str; 14 if (n == 0) 15 str = "0"; 16 while (n != 0) { 17 str.insert(str.begin(), '0' + n % 10); 18 n /= 10; 19 } 20 return str; 21 } 22 23 int main() { 24 while (true) { 25 string strList[16]; 26 int digCount[10]; 27 int j = 0, k = 0; 28 cin >> strList[0]; 29 if (strList[0][0] == '-') { 30 break; 31 } 32 int count = 0; 33 bool flag = false; 34 for (int i = 1; i < 16; ++i) { 35 for (int k = 0; k < 10; ++k) { 36 digCount[k] = 0; 37 } 38 for (int t = 0; t < strList[i - 1].size(); ++t) { 39 int d = strList[i - 1][t] - '0'; 40 ++digCount[d]; 41 } 42 strList[i] = ""; 43 for (int k = 0; k < 10; ++k) { 44 if (digCount[k] == 0) { 45 continue; 46 } 47 strList[i] += int2str(digCount[k]); 48 strList[i] += int2str(k); 49 } 50 if (strList[i] == strList[i - 1]) { 51 if (i == 1) { 52 cout << strList[0] << " is self-inventorying" << endl; 53 flag = true; 54 break; 55 } else { 56 cout << strList[0] << " is self-inventorying after " << i - 1 <<" steps" << endl; 57 flag = true; 58 break; 59 } 60 } 61 for (int j = 0; j < i; ++j) { 62 if (strList[i] == strList[j]) { 63 cout << strList[0] << " enters an inventory loop of length " << i - j << endl; 64 flag = true; 65 break; 66 } 67 } 68 if (flag == true) { 69 break; 70 } 71 } 72 if (flag == true) { 73 continue; 74 } else { 75 cout << strList[0] << " can not be classified after 15 iterations" << endl; 76 } 77 } 78 system("pause"); 79 }