題目
先吐槽一下:
這道題的英文我沒讀懂啥意思,后來去找了別人寫的中文,一下子也沒讀懂啥意思,什么鬼?
死命看題:
題目的意思是:
第一個數(shù)是給定的一個D,
那么第二個數(shù)的就是D1,原因是第一個數(shù)只有1個D;
第三個數(shù)是D111,原因是第二個數(shù)有1個D,和,1個1;
第四個數(shù)是D113,原因是第三個數(shù)有1個D,3個1;
第五個數(shù)是D11231,原因是第四個數(shù)有1個D,2個1,1個3;
...
到這里我好像明白題目的意思了,就是每一個數(shù)的構成都是要看上一個數(shù)有哪些數(shù)組成,形如:D+x1+x1的個數(shù)+x2+x2的個數(shù)...
但是!
第六個數(shù)的例子是D112213111,如果按照上述我理解的意思,那么應該是看第五個數(shù),有1個D,3個1,1個2,1個3;那么應該是D1132131,怎么回事?!為什么最后1個1不算進去?!
所以!真相是!
它的確是數(shù)個數(shù),但是數(shù)的是連續(xù)數(shù)的個數(shù)!
Sample Input
1 8
Sample Output
1123123111
解法
法一:C++
思路:
用vector,然后遍歷循環(huán)找出連續(xù)數(shù)的個數(shù),然后push_back進去。
說起來這么簡單,但是我被它的多個循環(huán)給搞暈了頭。(有預感以后的遞歸、動態(tài)規(guī)劃可能俺...)
吶,細細剖析循環(huán)的話是這樣的:
1.首先,要有個循環(huán)實現(xiàn)題目要求的求第n個數(shù)(發(fā)現(xiàn)寫循環(huán)的時候i<n-1才是第n個數(shù)!?。?br>
2.進入求第n個數(shù)后,要拿第n-1個數(shù)來循環(huán)找到第n-1個數(shù)的元素組成;而在這個循環(huán)中,目標是找到連續(xù)重復數(shù)的個數(shù),一旦不連續(xù)就得break;所以這里用while+for循環(huán)。
源代碼:
#include <iostream>
#include <cstdio>
#include <math.h>
#include<vector>
#include <string.h>
#include <sstream>
using namespace std;
int main() {
int d,n;
scanf("%d %d",&d,&n);
vector<int> sequence;
vector<int> temp;
int num,count,index;
num = d;
index=0;
sequence.push_back(d);
for(int i=0;i<n-1;i++){
num = sequence[0];
count = 0;
index = 0;
while (index != sequence.size()) {
for(int k=index;k<sequence.size();k++){
if(sequence[k] == num){
count++;
index++;
}
else{
break;
}
}
temp.push_back(num);
temp.push_back(count);
count = 0;
num = sequence[index];
}
sequence = temp;
temp.clear();
}
for (int i=0; i<sequence.size(); i++) {
cout<<sequence[i];
}
return 0;
}