题解【洛谷P5483】[JLOI2011]小A的烦恼

我们可以灵活运用\(C++\)的语法来解决此题。

解释一下代码中会出现的语法:

  1. \(string::iterator\ it\)表示定义了一个\(string\)类型的迭代器\(it\)\(^*it\)表示当前字符串的第\(it\)个元素。
  2. \(^*max\)_\(element(tot + 1,tot + m + 1)\)这个函数返回的是一个长的为\(m\)的数组\(tot\)中元素的最大值。

然后就是一些基本的模拟了。

\(AC\)代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>//头文件准备
#define itn int
#define gI gi

using namespace std;

inline int gi()
{
    int f = 1, x = 0; char c = getchar();
    while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar();}
    while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar();}
    return f * x;
}//快速读入

int n, m, tot[1005]/*每个文件中最大的列数*/, cnt, sum/*最大的行数*/;
string s, ans[1005]/*每一行的答案*/, tr;

int main()
{
    n = gi();
    for (itn i = 1; i <= n; i+=1)
    {
        m = gi(), cin >> s;
        memset(tot, 0, sizeof(tot));//记得清空数组
        ans[0] = ans[0] + s/*加上表头*/, sum = max(sum, m)/*计算最大的行数*/;
        for (int j = 1; j <= m; j+=1)
        {
            cin >> tr;//输入每行的元素
            ans[j] = ans[j] + tr;//先加入答案
            for (string :: iterator it = tr.begin(); it != tr.end(); it+=1)//遍历第j行
            {
                tot[j] = tot[j] + (*it == ',');//计算','分隔符个数
            }
        }
        cnt = *max_element(tot + 1,tot + m + 1);//得出最多的','分隔符数量
        for (int j = 0; j < 1005; j+=1)//枚举行。因为我们不知道最终答案的行数,因此就要枚举到最大的行数
        {
            for (int k = tot[j]; k <= ((i == n) ? (cnt - 1) : (cnt)); k+=1)//为答案增加','分隔符,注意判断i==n的情况,此时就要少加上一个','
            {
                ans[j] = ans[j] + ',';//加上','分隔符
            }
        }
    }
    for (int i = 0; i <= sum; i+=1)
    {
        cout << ans[i] << endl;//输出答案
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xsl19/p/11260819.html