题解
虽然要求一个dfs序,但是不是从根开始贪心
从最小的点开始贪心,最小的点显然是父亲选了之后马上就选它
那么我们每次把最小的点和父亲合并,两个联通块之间也是如此
对于两个联通块,他们合并的顺序应该是平均值较小的更靠前
因为有两个联通块和为(S_i)和(S_j),大小为(B_i)和(B_j)
如果(S_i * B_j < S_j * B_i)即(i)应该放在(j)前面,我们可以得到
(frac{S_i}{B_i} = frac{S_j}{B_j})
代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define pii pair<int,int>
#define space putchar(' ')
#define enter putchar('
')
#define mp make_pair
#define MAXN 500005
#define pb push_back
//#define ivorysi
using namespace std;
typedef long long int64;
template<class T>
void read(T &res) {
res = 0;char c = getchar();T f = 1;
while(c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
res = res * 10 + c - '0';
c = getchar();
}
res *= f;
}
template<class T>
void out(T x) {
if(x < 0) {putchar('-');x = -x;}
if(x >= 10) {
out(x / 10);
}
putchar('0' + x % 10);
}
struct node {
int to,next;
}E[MAXN * 2];
int N,head[MAXN],sumE;
int a[MAXN],siz[MAXN],fa[MAXN];
int64 w[MAXN],ans;
bool vis[MAXN];
struct cmp {
bool operator () (const int &a,const int &b) const {
return w[a] * siz[b] < w[b] * siz[a] || (w[a] * siz[b] == w[b] * siz[a] && a < b);
}
};
set<int,cmp> S;
void add(int u,int v) {
E[++sumE].to = v;
E[sumE].next = head[u];
head[u] = sumE;
}
void dfs(int u) {
vis[u] = 1;
for(int i = head[u] ; i ; i = E[i].next) {
int v = E[i].to;
if(!vis[v]) dfs(v);
}
}
int getfa(int u) {
return fa[u] == u ? u : fa[u] = getfa(fa[u]);
}
void Solve() {
read(N);
for(int i = 1 ; i <= N ; ++i) {read(a[i]);add(a[i],i);fa[i] = i;}
for(int i = 1 ; i <= N ; ++i) {read(w[i]);}
dfs(0);
for(int i = 1 ; i <= N ; ++i) {
if(!vis[i]) {puts("-1");return;}
}
for(int i = 0 ; i <= N ; ++i) siz[i] = 1;
for(int i = 1 ; i <= N ; ++i) S.insert(i);
for(int i = 1 ; i <= N ; ++i) {
int v = *S.begin();
S.erase(S.begin());
int u = getfa(a[v]);
if(u) S.erase(u);
ans += siz[u] * w[v];
w[u] += w[v];siz[u] += siz[v];fa[v] = u;
if(u) S.insert(u);
}
out(ans);enter;
}
int main() {
#ifdef ivorysi
freopen("f1.in","r",stdin);
#endif
Solve();
}