poj1016 模拟

题意:对数字进行压缩,如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;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kangwq2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值