Educational Codeforces Round 93-C

题目链接

比赛的时候只想到了对每一个字符-1的操作,但是后续的处理完全是在抓瞎,始终只能想到O(n²)的暴力做法,赛后补题发现了map的妙用;

解题思路
对 给定字符串每个数的值-1(长度),题目就从 求 满足(子区间元素和=子区间长度)的子区间数量
变为了 求满足子区间和为0的子区间数量
对前缀和进行处理,如果两个前缀和相等,中间区间的和一定为0;
用map记录相同前缀的数量;
在循环中 ans+=map[前缀],得到的即为答案

如果在循环外求取ans
设每个前缀的值为ni
应该要遍历map中的每一个前缀,ans+=(1+2+3……+(ni-1))=(ni-1)*ni/2;

此外,mp[0]要初始化为1,否则单个区间(第一个)的值为0的时候 答案值会出错

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
const int maxn=1e5+50;
const int inf=0x3f3f3f3f;
const int MOD=10007;
 
int main()
{
     
    int t;
    scanf("%d",&t);
    while(t--)
    {
     
        int len;
        scanf("%d",&len);
        char s[maxn];
        scanf("%s",s);
        ll ans=0;
        int a=0;
        map<int,int> mp;//mp记录(前缀和-长度)出现的次数
        mp[0]++;//联系下面,考虑一开始(a-(i+1))为0的情况
        for(int i=0;i<len;i++)
        {
     
            a+=s[i]-'0';//a为前缀和
            ans+=mp[a-(i+1)];
            mp[a-1-i]++;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(水题记录)