题意:对数字进行压缩,如1111111和21221314,分别可以压缩为71和31321314。对给定的一数字n,如果压缩前后相等,如22,输出n is self-inventorying,如果经过j次压缩后值不再变化,输出n is self-inventorying after j steps,如果形成循环,输出n enters an inventory loop of length k,如果经过15次压缩后不存在上述三种情况,输出n can not be classified after 15 iterations
算法:模拟。为得到数字n压缩后的值,我们借助一个整形数组a,如21221314,可以得到如下数组:
1 3
2 3
3 1
4 1
由该数组我们可以得到21221314压缩后的值为31321314。
重复此过程,即可知结果。
#include <iostream>
#include <string.h>
using namespace std;
char n[15][100];
int a[15][100];
// 根据数组a[i]得到数组n[j]
int aton(int ai, int nj)
{
int j=0;
for (int i=0; i<=9; i++)
{
if (a[ai][i] > 0)
{
if (a[ai][i] < 10)
{
n[nj][j++] = a[ai][i]+'0';
n[nj][j++] = i+'0';
}
else
{
n[nj][j++] = a[ai][i] / 10 + '0';
n[nj][j++] = a[ai][i] % 10 + '0';
n[nj][j++] = i+'0';
}
}
}
n[nj][j] = '\0';
return j;
}
// 根据数组n[i]得到数组a[j]
void ntoa(int ni, int aj, int len)
{
for (int i=0; i<len; i++)
{
a[aj][n[ni][i]-'0']++;
}
}
int main()
{
while (cin >> n[0] && n[0][0] != '-')
{
memset(a,0,sizeof(a));
int len = strlen(n[0]);
ntoa(0,0,len);
aton(0,1);
// 先判断是否是self-inventorying
if (strcmp(n[0],n[1]) == 0)
{
cout << n[0] << " is self-inventorying" << endl;
continue;
}
bool ans = false;
for (int i=2; i<=15 && !ans; i++)
{
memset(a,0,sizeof(a));
len = strlen(n[i-1]);
// 根据n[i-1]求出a[i-1],再根据a[i-1]求出n[i],然后进行判断
ntoa(i-1,i-1,len);
aton(i-1,i);
if (strcmp(n[i-1],n[i]) == 0)
{
cout << n[0] << " is self-inventorying after " << i-1 << " steps" << endl;
ans = true;
continue;
}
for (int k=0; k<i; k++)
{
if (strcmp(n[i],n[k]) == 0)
{
cout << n[0] << " enters an inventory loop of length " << i-k << endl;
ans = true;
break;
}
}
}
if (!ans)
{
cout << n[0] << " can not be classified after 15 iterations" << endl;
}
}
}