#include <bits/stdc++.h>
#define ll long long
#define pb push_back
using namespace std;
ll n,a[100005],ans,pat[1000005][25],cnt[100005];
vector<ll>v[100005];
ll qr(ll cnt1,ll x[],ll cnt2,ll y[]){
ll ret=0;
for(ll i=0;i<25;i++){
ll b=x[i]*(cnt2-y[i])+y[i]*(cnt1-x[i]);
ret+=b*(1<<i);
}
return ret;
}
void xorr(ll x,ll cnt,ll a[]){
for(ll i=0;i<25;i++){
if(((1<<i)&x)==0)continue;
a[i]=cnt-a[i];
}
}
void add(ll x[],ll y[]){
for(ll i=0;i<25;i++){
x[i]+=y[i];
}
}
void dfs(ll nod,ll par){
ans+=a[nod];
cnt[nod]=1;
for(ll i=0;i<25;i++){
pat[nod][i]=(bool)(a[nod]&(1<<i))!=0;
}
for(auto ch:v[nod]){
if(ch==par)continue;
dfs(ch,nod);
ans+=qr(cnt[nod],pat[nod],cnt[ch],pat[ch]);
xorr(a[nod],cnt[ch],pat[ch]);
add(pat[nod],pat[ch]);
cnt[nod]+=cnt[ch];
}
}
int main(){
cin>>n;
for(ll i=1;i<=n;i++){
cin>>a[i];
}
for(ll i=0;i<n-1;i++){
ll a,b;
cin>>a>>b;
v[a].pb(b);
v[b].pb(a);
}
dfs(1,0);
cout<<ans<<endl;
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
5 ms |
2688 KB |
Output is correct |
2 |
Correct |
5 ms |
2688 KB |
Output is correct |
3 |
Correct |
4 ms |
2688 KB |
Output is correct |
4 |
Correct |
7 ms |
3072 KB |
Output is correct |
5 |
Correct |
5 ms |
2944 KB |
Output is correct |
6 |
Correct |
172 ms |
36856 KB |
Output is correct |
7 |
Correct |
168 ms |
36636 KB |
Output is correct |
8 |
Correct |
240 ms |
30852 KB |
Output is correct |
9 |
Correct |
181 ms |
30072 KB |
Output is correct |
10 |
Correct |
216 ms |
29392 KB |
Output is correct |