文章目录
Author: CHEN, Yue
Organization: 浙江大学
Time Limit: 400 ms
Memory Limit: 64 MB
Code Size Limit: 16 KB
A1140 Look-and-say Sequence (20point(s))
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
Code
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
vector<int> num,tempNum;
int main(){
int d,n;
scanf("%d %d",&d,&n);
num.push_back(d);
for(int i=0;i<n-1;i++){
int cnt=0,pre=num[0];
tempNum.clear();
for(int j=0;j<num.size();j++){
if(i==0){
tempNum.push_back(pre);
tempNum.push_back(1);
}
else{
if(j!=num.size()-1){
if(pre==num[j]) cnt++;
else{
tempNum.push_back(pre);
tempNum.push_back(cnt);
pre=num[j];
cnt=1;
}
}
else if(j==num.size()-1){
if(pre==num[j]){
cnt++;
tempNum.push_back(pre);
tempNum.push_back(cnt);
}
else{
tempNum.push_back(pre);
tempNum.push_back(cnt);
tempNum.push_back(num[j]);
tempNum.push_back(1);
}
}
}
}
num=tempNum;
}
for(int i=0;i<num.size();i++) printf("%d",num[i]);
return 0;
}
Analysis
-已知两个数字D和n。
-每次变化时把这个字符串中字符相同的连续一段映射成字符和连续个数生成新字符串。
视D为第一个字符串,则:
第一个字符串为 D;
第二个字符串为 D1;
第三个字符串为 D1 11 (空格仅用作强调,实际输出时没有);
第四个字符串为 D1 13;
第五个字符串为 D1 12 31;
第六个字符串为 D1 12 21 31 11;
……