题解:P1320 压缩技术(续集版)

· · 题解

思路

先读入一行字符串 b,容易发现,这一行字符串的长度就是 N。接着继续读入字符串

while(cin>>a){
    b+=a;
}

这一步的目的是将多行字符串拼接为一行。

接下来特判:如果 b_0 也就是字符串的第一位不是 0,那么 0 的数量就是 0,要先输出。

if(b[0]!='0') cout<<"0 ";

然后遍历字符串从 b_1b_{N^2},用变量 t(初始为 1)记录,如果 b_i=b_{i-1},那么 t 增加,否则输出 t,将 t 赋值为 1

循环结束后不要忘记在输出 t

代码

#include<iostream>
#include<string>
using namespace std;
int n,x,num=0,t=1,ans=0,cnt=1;
string a,b;
int main(){
    cin>>b;
    n=b.size();
    cout<<n<<" ";
    while(cin>>a){
        b+=a;
    }
    if(b[0]!='0') cout<<"0 ";
    for(int i=1;i<n*n;i++){
        if(b[i]==b[i-1]){
            t++;
        }
        else{
            cout<<t<<" ";
            t=1;
        }
    }
    cout<<t;
    return 0;
}