题意
题目的意思很简单,就是对字符串的反复压缩。比如,5553141里面有2个1,1个3,1个4,3个5,所以压缩一下变为21131435,接着压缩变为3112231415,4122231415,3132132415,3122331415,3122331415,直到出现自身循环,或者像314213241519→412223241519→314213241519出现loop为2的循环,最大迭代次数为15,
分析
比较简单,直接上代码:
Memory: 232K Time: 79MS Length:50LINES
#include<iostream>
#include<string>
using namespace std;
int Search(const string* vecstr, string str, int k) //搜索有没有出现循环
{
int i = 0;
for (; i < k; ++i) if (vecstr[i] == str) break;
return i;
}
int main()
{
string input;
while (cin >> input && input[0] != '-')
{
string temp = input;
string vecstr[16] = { "" };
int count = 0;
do
{
vecstr[count] = temp;
int number[10] = { 0 };
for (string::size_type i = 0; i < temp.length(); ++i) ++number[temp[i] - 48]; //统计每个字符出现的次数
temp = "";
for (int i = 0; i < 10; ++i)
{
if (number[i] == 0) continue;
if (number[i] >= 10)
{
temp += number[i] / 10 + 48;
temp += number[i] % 10 + 48;
}
else temp += number[i] + 48;
temp += i + 48; //组成新的字符串
}
++count;
} while (Search(vecstr, temp, count) == count && count <= 15);
if (count > 15)
cout << input << " can not be classified after 15 iterations" << endl;
else if (count == 1)
cout << input << " is self-inventorying" << endl;
else if (Search(vecstr, temp, count) == count - 1)
cout << input << " is self-inventorying after " << count - 1 << " steps" << endl;
else
{
cout << input << " enters an inventory loop of length ";
cout << count - Search(vecstr, temp, count) << endl;
}
}
return 0;
}