前缀和+哈希表

前缀和+哈希表
CCPC网络赛链接

#include<bits/stdc++.h>
#define p 1e6
#define ll long long
using namespace std;
int n;
string s;
int T;
map<ll,ll>m;
void solve(){
    
    
    long long ans=0;
    cin>>n>>s;
    m.clear();
    m[0]=1;
    long long v=0;
    for(auto c:s){
    
    
        if(c=='U')v+=1;
        if(c=='D')v-=1;
        if(c=='L')v+=1000000;
        if(c=='R')v-=1000000;
        //cout<<"ans="<<ans<<"  "<<"m["<<v<<"]="<<m[v]<<endl;
        ans+=m[v];
        m[v]=m[v]+1;
        //cout<<"ans="<<ans<<"  "<<"m["<<v<<"]="<<m[v]<<endl;
    }
    //ans+=m[v];
    printf("%lld\n",ans);
}
signed main(){
    
    
    cin>>T;
    while(T--)solve();
}




给定长度为n的a数组,和k
求有多少个子序列异或和等于k即
a[l] ^ a[l+1] ^ a[l+2] ^ … ^ a[r] = k
https://acm.webturing.com/problem.php?cid=1700&pid=7

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,k,a[200010],ans;
unordered_map<int,int>mp;
signed main(){
    
    
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++){
    
    
        cin>>a[i];
        a[i]^=a[i-1];
    }
    cin>>k;
    mp[0]=1;
    for(int i=1;i<=n;i++){
    
    
        ans+=mp[a[i]^k];
        mp[a[i]]++;
    }
    cout<<ans;
}

猜你喜欢

转载自blog.csdn.net/supreme567/article/details/124874094