题解:P11138 [APC001] C - Not APC

· · 题解

第一眼:太简单了。

第二眼:要 O(n)?

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

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

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

不懂的话看代码:

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  ---------- */

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