題目大意:給定一個長度爲 N 的序列,每一個位置有一個權值,求 $$\sum\limits_{1\le i\le j\le n}(a_i\oplus a_{i+1}...\oplus a_j)$$ 的值。c++
題解: 解法1:從總體考慮。 先預處理出序列的前綴異或和。根據和式的性質可知,對於任意兩個點 i,j 的組合均會計入答案貢獻,而異或值爲 1 纔會對答案產生貢獻。所以,統計出對於32位中的每一位來講,前綴和序列中該位爲 1 的個數。最後根據組合計數原理,每一位對答案的貢獻爲該位 1 的個數乘以該位 0 的個數乘以對應的 2 的冪便可。git
代碼以下spa
#include <bits/stdc++.h> #define fi first #define se second #define pb push_back #define mp make_pair #define all(x) x.begin(),x.end() #define cls(a,b) memset(a,b,sizeof(a)) using namespace std; typedef long long ll; typedef pair<int,int> P; const int dx[]={0,1,0,-1}; const int dy[]={1,0,-1,0}; const int mod=1e9+7; const int inf=0x3f3f3f3f; const int maxn=1e5+10; const double eps=1e-6; inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} inline ll sqr(ll x){return x*x;} inline ll fpow(ll a,ll b,ll c){ll ret=1%c;for(;b;b>>=1,a=a*a%c)if(b&1)ret=ret*a%c;return ret;} inline ll read(){ ll x=0,f=1;char ch; do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch)); do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch)); return f*x; } /*------------------------------------------------------------*/ int n,a[maxn]; ll cnt[30]; void read_and_parse(){ n=read(); for(int i=1;i<=n;i++)a[i]=read()^a[i-1]; } void solve(){ for(int i=1;i<=n;i++) for(int j=0;j<30;j++) if(a[i]>>j&1)++cnt[j]; ll ans=0; for(int i=0;i<30;i++)ans+=cnt[i]*(n+1-cnt[i])*(1LL<<i); printf("%lld\n",ans); } int main(){ read_and_parse(); solve(); return 0; }
解法2:將問題劃分爲若干子問題。code
代碼以下get
#include <bits/stdc++.h> #define fi first #define se second #define pb push_back #define mp make_pair #define all(x) x.begin(),x.end() #define cls(a,b) memset(a,b,sizeof(a)) using namespace std; typedef long long ll; typedef pair<int,int> P; const int dx[]={0,1,0,-1}; const int dy[]={1,0,-1,0}; const int mod=1e9+7; const int inf=0x3f3f3f3f; const int maxn=1e5+10; const double eps=1e-6; inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} inline ll sqr(ll x){return x*x;} inline ll fpow(ll a,ll b,ll c){ll ret=1%c;for(;b;b>>=1,a=a*a%c)if(b&1)ret=ret*a%c;return ret;} inline ll read(){ ll x=0,f=1;char ch; do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch)); do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch)); return f*x; } /*------------------------------------------------------------*/ int n,a[maxn]; ll ans; void read_and_parse(){ n=read(); for(int i=1;i<=n;i++)a[i]=read(); } void solve(){ for(int i=0;i<30;i++){ ll sum=0,now=0; for(int j=1;j<=n;j++){ if(a[j]>>i&1)now=j-now; sum+=now; } ans+=(ll)sum*(1<<i); } printf("%lld\n",ans); } int main(){ read_and_parse(); solve(); return 0; }