# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1010949 | imarn | JOI tour (JOI24_joitour) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("avx2")
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define plx pair<ll,int>
#define f first
#define s second
#define pb push_back
#define all(x) x.begin(),x.end()
#define vi vector<int>
#define vl vector<ll>
#define vvi vector<vi>
using namespace std;
const int mxn=2e5+5;
vector<int>g[mxn],f;
int sz[mxn]{0};
bool vis[mxn]{0};
unsigned ll ans=0;
int getsz(int u,int p){
sz[u]=1;
for(auto v:g[u])if(v!=p&&!vis[v])sz[u]+=getsz(v,u);
return sz[u];
}
int getct(int u,int p,int r){
for(auto v:g[u])if(v!=p&&!vis[v]&&sz[v]*2>r)return getct(v,u,r);
return u;
}
vector<ll>dp[10][mxn];
ll td[10][mxn]{0};
void gen1(int u,int p,int x,int id){
dp[f[u]][x][id]++;
if(f[u]==2)dp[3][x][id]+=dp[1][x][id];
if(f[u]==1)dp[4][x][id]+=dp[0][x][id];
for(auto v:g[u])if(v!=p&&!vis[v])gen1(v,u,x,id);
dp[f[u]][x][id]--;
}
void gen2(int u,int p,int x,int id){
for(auto v:g[u])if(v!=p&&!vis[v])gen2(v,u,x,id);
dp[f[u]+5][x][id]++;
if(f[u]==1)dp[8][x][id]+=dp[5][x][id];
if(f[u]==2)dp[9][x][id]+=dp[6][x][id];
}
void gen3(int u,int p,int x,int id){
dp[f[u]][x][id]++;
for(auto v:g[u])if(v!=p&&!vis[v])gen3(v,u,x,id);
}
void play(int u){int id=-1;
u = getct(u,u,getsz(u,u));vis[u]=1;
for(auto v:g[u]){
if(vis[v])continue;
for(int i=0;i<10;i++)dp[i][u].pb(0);id++;
gen1(v,u,u,id);gen2(v,u,u,id);gen3(v,u,u,id);
for(int i=0;i<10;i++)td[i][u]+=dp[i][u][id];
}for(int j=0;j<=id;j++){
ans+=dp[0][u][j]*(td[3][u]-dp[3][u][j]);
ans+=dp[8][u][j]*(td[2][u]-dp[2][u][j]);
if(f[u]==1)ans+=dp[0][u][j]*(td[2][u]-dp[2][u][j]);
}if(f[u]==0)ans+=td[3][u];if(f[u]==2)ans+=td[8][u];
for(auto v:g[u])if(!vis[v])play(v);
}
void init(int N, std::vector<int> F, std::vector<int> U, std::vector<int> V,int Q){
f=F;for(int i=0;i<N-1;i++)g[U[i]].pb(V[i]),g[V[i]].pb(U[i]);play(0);
}
void change(int X, int Y) {}
long long num_tours() {
return ans;
}
int main(){
int n;cin>>n;
vector<int>ff(n,0),u(n-1),v(n-1);
for(int i=0;i<n;i++)cin>>ff[i];
for(int i=0;i<n-1;i++)cin>>u[i]>>v[i];
init(n,ff,u,v,0);cout<<ans;
}