跳到正文

题解

题解:P11138 [APC001] C - Not APC

jianghz约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年10月2日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
1
题目
P11138

版本

  1. v1当前

第一眼:太简单了。

第二眼:要 O(n)O(n)?

然后就诞生了这篇题解。(本人是蒟蒻,有错请指出)


首先,根据数据规模,我们判断出要用 O(n)O(n) 的算法。

  1. 考虑定义两个队列 x,yx,y,xx 存储 A 的出现位置,yy 存储 P 的出现位置,定义两个变量 a,p,apa,p,ap,分别表示 x,yx,y 的长度,以及 aa 与 pp 的差。
  2. 对于每一个字符,如果这个字符是 A,索引进队列 xx,a++; ap++。
  3. 如果这个字符是 P,且 apap 不为 00,此时队列 xx 中有未匹配的 A,索引进队列 yy,p++; ap--。
  4. 如果这个字符是 C,且 a,pa,p 不为 00,此时有未匹配的 A,P。用 xx 的队首和 yy 的队首,和当前索引组成一个三元组,这就是一组答案。
  5. 最后把没删除的输出出来,或输出 Perfect,然后输出你的所有删除的项即可。

不懂的话看代码:

C++
struct node{
    int a, p, c;
};
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:  
 * =====================================================================================
 */
int main ( int argc, char *argv[] )
{ 
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen(".in", "r", stdin);
    //freopen(".out", "w", stdout);
    int t;
    cin >> t;
    while (t--){
        queue < int > x, y;
        vector < node > ans;
        string s;
        cin >> s;
        int n = size(s);
        bool d[n + 5]{};
        int a = 0, p = 0, ap = 0;
        for (int i = 0; i < n; i++){
            if (s[i] == 'A'){
                a++;
                ap++;
                x.push(i);
            }
            if (s[i] == 'P' && ap){
                p++;
                ap--;
                y.push(i);
            }
            if (s[i] == 'C' && a && p){
                a--, p--;
                ans.push_back({x.front(), y.front(), i});
                d[x.front()] = 1; d[y.front()] = 1; d[i] = 1;
                x.pop(); y.pop();
            }
        }
        int f = 0;
        for (int i = 0; i < n; i++)
            if (!d[i]){
                cout << s[i];
                f++;
            }
        if (!f)
            cout << "Perfect";
        cout << endl;
        cout << size(ans) << endl;
        for (int i = 0; i < size(ans); i++)
            cout << ans[i].a + 1 << " " << ans[i].p + 1 << " " << ans[i].c + 1 << endl;
    }
    //fclose(stdin);
    //fclose(stdout);
    return 0;
}				/* ----------  end of function main  ---------- */

代码都看完了,点个赞不过分吧。

原文
存档评论1 条抓取于