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

· · 题解

题目简述

题意

给定一个若干大小的矩阵,按照以下要求输出。

接下来输入 n-1 行,为了便于处理,直接把输入的整个字符串全部加到字符串 str 里。

定义 cnt,用于记录相同字符的数量,初值为 1

接下来遍历 str,如果 str_{i-1} 等于 str_i,令 cnt \gets cnt+1,否则输出 cnt,并令 cnt \gets 1,因为当我们进行下一次判断时,str_i 也要算上。

AC 代码

#include <bits/stdc++.h>
using namespace std;
#define in cin
#define out cout

int main() {
    string x, s = "";
    in >> x;
    s += x;
    for (int i = 1; i < x.size(); i++) { //输入字符串
        string str;
        in >> str;
        s += str; //并把str加到s里
    }
    out << int(x.size()) << ' '; //输出N
    int cnt = 1;
    if (s[0] == '1')
        out << "0 ";
    for (int i = 1; i < s.size(); i++) //遍历s
        if (s[i - 1] != s[i]) { //如果不等
            out << cnt << ' '; //输出cnt
            cnt = 1; //令cnt=1
        } else
            cnt++; //否则+1
    out << cnt; //输出最后的数量
    return 0;
} =