NOI2020训练题4 A 解放

题目描述:

输入格式:

输出格式:

样例输入:

3
1 2 1
2 3 1
1 3 2

样例输出:

0
2
2

数据范围:

时间限制:
1s

空间限制:
64MB

Solution

我们把第一个占领的点作为树的根,然后每占领一个点,相当于就要不断向父亲连边,直到形成一个联通块。

每条边最多连一次。复杂度\(O(n)\)


#include<bits/stdc++.h>
using namespace std;

const int N = 1e6 + 10;

int n;
struct Edge{
    int to,nxt,v;
}edge[N << 1];
int head[N];
int tmp;
void add(int x,int y,int z){
    ++ tmp;
    edge[tmp].to = y; edge[tmp].nxt = head[x]; edge[tmp].v = z;
    head[x] = tmp;
}
int a[N];

int fa[N],fav[N],okfa[N];
void dfs1(int nod,int f){
    fa[nod] = f; okfa[nod] = 0;
    for(int i = head[nod]; i != -1; i = edge[i].nxt){
        int t = edge[i].to;
        if(t == f) continue;
        fav[t] = edge[i].v; dfs1(t,nod);
    }
}

int main(){
	tmp = 0; memset(head,-1,sizeof(head));
	scanf("%d",&n);
	for(int i = 1; i < n; ++ i){
	    int x,y,z; scanf("%d%d%d",&x,&y,&z);
	    add(x,y,z); add(y,x,z);
	}
	for(int i = 1; i <= n; ++ i) scanf("%d",&a[i]);
	
	printf("0\n");
    
	dfs1(a[1],0);
	okfa[a[1]] = 1;
	
	long long ans = 0;
	for(int i = 2; i <= n; ++ i){
	    int x = a[i];
	    
	    while(!okfa[x]) { ans += fav[x]; okfa[x] = 1; x = fa[x]; }
	    printf("%lld\n",ans);
	}
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zzhzzh123/p/13399111.html