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
.
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;
}