PAT 1140 Look-and-say Sequence [字符串处理] [模拟]

本文详细解析了一种特殊的数列——Look-and-say数列的生成规则,并通过一个具体的示例,即输入数字18,展示了如何使用C++编程语言实现该数列的计算过程。文章首先介绍了数列的基本概念,随后通过代码示例,演示了如何通过迭代的方式生成数列中指定位置的元素。

Look-and-say sequence is a sequence of integers as the following:

D, D1, D111, D113, D11231, D112213111, ...

where D is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one Din the 1st number, and hence it is D1; the 2nd number consists of one D(corresponding to D1) and one 1 (corresponding to 11), therefore the 3rd number is D111; or since the 4th number is D113, it consists of one D, two 1's, and one 3, so the next number must be D11231. This definition works for D = 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D.

Input Specification:

Each input file contains one test case, which gives D (in [0, 9]) and a positive integer N (≤ 40), separated by a space.

Output Specification:

Print in a line the Nth number in a look-and-say sequence of D.

Sample Input:

1 8

Sample Output:

1123123111

--------------------------------------这是题目和解题的分割线--------------------------------------

又是一道需要花点点时间理解意思的题目。其实也很简单啦,简言之,现在对过去的描述。

具体展开的话,就不拿题目给的Dxxx模拟了,直接用输入输出的数字吧~ 输入是:1 8,说明 ① 1

①里有1个1 所以是 ② 11

②里有2个1 所以是 ③ 12

③里有1个1和1个2 所以是 ④ 1121(数字放前面次数放后面)

④里有2个1和1个2和1个1 所以是 ⑤ 122111 (不是算总共多少个1哦必须要连在一起才行)

......以此类推

这里参考了这位博友【我怎么又在看别人的代码= = 

用vector或者string都可以很方便地进行实时相加。

#include<cstdio>
#include<vector>
#include<iostream>

using namespace std;

int main()
{
	//tmp存取当前状态,str存取上一次的状态 
	vector<int> tmp,str;
	int n,m;
	cin>>n>>m;
	//先存取第一次的状态 
	str.push_back(n);
	//存取了第一次,所以循环是m-1次 
	for(int i=1;i<m;i++)
	{
		//x存取当前比较的数字,cnt存取出现次数 
		int x = str[0],cnt = 0;
		//遍历当前状态的一连串数字 
		for(int j=0;j<str.size();j++)
		{
			//如果是连续相同的数字,累加 
			if(str[j]==x)
				cnt++;
			//如果遇到了不同的数字 
			else
			{
				//将之前相同的数字存取下来 
				tmp.push_back(x);
				//注意是先存数字再存次数 
				tmp.push_back(cnt);
				//cnt = 1 ≠0
				//此时str[j]是第一个不同的数字,必须也记录上 
				cnt = 1;
				//更新需要比较的数字 
				x = str[j];
			}
			//由于在出现了不同数字后才进行存取,所以得单独处理一下末尾的数字串 
			if(j==str.size()-1)
			{
				tmp.push_back(x);
				tmp.push_back(cnt);
			}
		}
		//更新上一次的状态 
		str = tmp;
		//记得清空,不然会有影响 
		tmp.clear();
	}
	for(int i=0;i<str.size();i++)
		cout<<str[i];
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值