专题测试四 dp与贪心 A - QAQ

  1. 题目

    "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.

    Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).

    illustration by 猫屋 https://twitter.com/nekoyaliu

    Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.

    Input

    The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.

    Output

    Print a single integer — the number of subsequences "QAQ" in the string.

    Sample 1
    Input Output
    QAQAQYSYIOIWIN
    
    4
    
    Sample 2
    Input Output
    QAQQQZZYNOIWIN
    
    3
    
    Note

    In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN".

  2. 思路
    二刺猿真的是💧
    要构成一个QAQ,只需要一个A以及在它两边的Q,对于每个A,构成QAQ的数量就是在它左边的Q的数量乘以右边Q的数量(排列组合一下),将所有A的QAQ数量加起来就可以了,可以用前缀和表示从第一个到第i个Q的数量
  3. 代码
    #include<cstdio>
    #include<iostream>
    #include<string>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    
    #define Clear(a) memset(a,0,sizeof(a))
    
    const int maxn = 250;
    char str[maxn] ;
    int sum[maxn] ;
    
    int main()
    {
        scanf("%s",str);
        Clear(sum);
        int num = 0;
        int len = strlen(str);
        for(int i=0;i<len;i++)
    	{
            if(str[i] =='Q')
    		{
                num ++ ;
            }
            sum[i] = num ;
        }
        long long ans = 0 ;
        for(int i=0;i<len;i++)
    	{
            if(str[i] =='A')
            ans += sum[i] * (sum[len - 1] - sum[i]);
        }
    
            printf("%lld\n", ans) ;
        return 0;
    }
posted @ 2022-02-17 12:47  Benincasa  阅读(43)  评论(0编辑  收藏  举报