luogu P3320 [SDOI2015]寻宝游戏

大意:给定树, 要求维护一个集合, 支持增删点, 询问从集合中任取一点作为起点, 遍历完其他点后原路返回的最短长度.

 

集合中的点按$dfs$序排列后, 最短距离就为$dis(s_1,s_2)+...+dis(s_k,s_1)$

 

#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
#define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;})
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;}
//head



#ifdef ONLINE_JUDGE
const int N = 1e6+10;
#else
const int N = 111;
#endif

int n, m;
int sz[N], dep[N], fa[N];
ll w[N];
int son[N], top[N], L[N], R[N];
struct _ {int to,w;};
vector<_> g[N];
void dfs(int x, int f, int d) {
	sz[x]=1,fa[x]=f,dep[x]=d,L[x]=++*L;
	for (_ e:g[x]) if (e.to!=f) {
		int y = e.to;
		w[y]=w[x]+e.w;
		dfs(e.to,x,d+1),sz[x]+=sz[y];
		if (sz[y]>sz[son[x]]) son[x]=y;
	}
}
void dfs(int x, int tf) {
	top[x]=tf;
	if (son[x]) dfs(son[x],tf);
	for (_ e:g[x]) if (!top[e.to]) dfs(e.to,e.to);
}
int lca(int x, int y) {
	while (top[x]!=top[y]) {
		if (dep[top[x]]<dep[top[y]]) swap(x,y);
		x = fa[top[x]];
	}
	return dep[x]<dep[y]?x:y;
}
ll dis(int x, int y) {return w[x]+w[y]-2*w[lca(x,y)];}
struct cmp {
	bool operator () (const int & x, const int & y) const {
		return L[x]<L[y];
	}
};
set<int,cmp> s;
ll ans;
void solve(int x) {
	int f = s.count(x)?-1:1;
	if (f==1) s.insert(x);
	auto t = s.lower_bound(x);
	int L, R, A = *s.begin(), B = *--s.end();
	if (s.size()==1) ;
	else if (s.size()==2) {
		if (x==A) ans+=2*f*dis(x,B);
		else ans+=2*f*dis(A,x);
	}
	else { 
		if (x==B) L=*--t,R=A;
		else if (x==A) L=B,R=*++t;
		else L=*--t,R=*++++t;
		ans += f*(dis(L,x)+dis(x,R)-dis(L,R));
	}
	if (f==-1) s.erase(x);
}
int main() {
	scanf("%d%d", &n, &m);
	REP(i,2,n) {
		int u, v, w;
		scanf("%d%d%d", &u, &v, &w);
		g[u].pb({v,w}),g[v].pb({u,w});
	}
	dfs(1,0,0),dfs(1,1);
	REP(i,1,m) {
		int x;
		scanf("%d", &x);
		solve(x);
		printf("%lld\n", ans);
	}
}

 

posted @ 2019-05-13 10:02  uid001  阅读(126)  评论(0编辑  收藏  举报