PAT-A1140 Look-and-say Sequence (20分)

题目描述:
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 D in 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.

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

输出格式:
Print in a line the Nth number in a look-and-say sequence of D.

输入样例:
1 8

输出样例:
1123123111

题意:
给出D为第1个数,求第N个数。规则如下(假设D不为1):
假设第1个数为D,那么第2个数是D1,因为在第1个数中,D有1个;
第3个数为D111,因为在第2个数中,D有1个,1有1个;
第4个数为D113,因为在第3个数中,D有1个,1有3个;
以此从左到右类推,不相邻的相同数字分开计算,详见样例解释。
D为1时同样可以用这个方法递推。

样例解释:
给出1为第1个数,求第8个数。
因为第1个数为1,1有1个,所以第2个数为11;
因为第2个数为11,1有2个,所以第3个数为12;
因为第3个数为12,1有1个,2有1个,所以第4个数为1121;
因为第4个数为1121,1有2个,2有1个,1有1个,所以第5个数为122111;
因为第5个数为122111,1有1个,2有2个,1有3个,所以第6个数为112213;
因为第6个数为112213,1有2个,2有2个,1有1个,3有1个,所以第7个数为12221131;
因为第7个数为12221131,1有1个,2有3个,1有2个,3有1个,1有1个。所以第8个数为1123123111;
输出1123123111。

思路:
运用了队列queue和可变化数组vector,首先将D存入队列中,因为求的是第N个数,所以要进行N-1次循环。在每个循环中,依次出队列,按顺序判断每个特定的值有几个,存入数组,当队列空后,将数组的值依次赋给队列,清除数组,进入下一层循环,详见代码。

参考代码:

#include 
#include 
#include  
using namespace std;
vector<int> temp; //临时存放每次的序列
queue<int> seq; //按顺序读取数字

int main(){
	int d, n; //初始值,第n个数字
	scanf("%d%d", &d, &n);
	seq.push(d);
	int idx = d; //特定的数字 
	for(int i = 1; i < n; i++){
		int cnt = 0; //特定数字的数量
		while(!seq.empty()){
			int now = seq.front();
			seq.pop();
			if(now == idx){
				cnt++;
			}else{
				temp.push_back(idx);
				temp.push_back(cnt);
				cnt = 1;
				idx = now;
			}
		}
		temp.push_back(idx);
		temp.push_back(cnt);
		int len = temp.size();
		if(len > 0) idx = temp[0]; //下次的初始值是这次存入的第1个数
		for(int j = 0; j < len; j++){
			seq.push(temp[j]);
		}
		temp.clear(); //因为多次使用,所以每次使用完毕要及时清除
	} 
	//输出最终结果
	while(!seq.empty()){
		int now = seq.front();
		printf("%d", now);
		seq.pop();
	}
	return 0;
}

你可能感兴趣的:(PAT-A1140 Look-and-say Sequence (20分))