BZOJ3910 火车

8 篇文章 0 订阅
5 篇文章 0 订阅

先orz小火车IOI rank2……

傻逼我做法:LCT维护链染色和查询单点颜色,链长度

orz commonc做法:以起点为根建树,一个点没被走过的充要条件是他的子树内没有点被作为过行进目标,拿树状数组搞就好了

其实用并查集搞也可以

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<vector>
#include<set>
#include<bitset>
#include<queue>
#include<stack>
#include<map>
using namespace std;
#define MAXN 500010
#define MAXM 1010
#define eps 1e-8
#define ll long long
#define INF 1000000000
#define MOD 1000000007
#define lb(x) x&-x
struct vec{
	int to;
	int fro;
};
vec mp[MAXN*2];
int tai[MAXN],cnt;
int n,m,s;
int fa[MAXN][21],dep[MAXN],siz[MAXN],dfn[MAXN],tim;
int c[MAXN];
ll ans;
void change(int x){
	for(;x<=n;x+=lb(x)){
		c[x]++;
	}
}
int ask(int x){
	int re=0;
	for(;x;x-=lb(x)){
		re+=c[x];
	}
	return re;
}
inline void be(int x,int y){
	mp[++cnt].to=y;
	mp[cnt].fro=tai[x];
	tai[x]=cnt;
}
inline void bde(int x,int y){
	be(x,y);
	be(y,x);
}
void dfs(int x){
	int i,j,y,t;
	dfn[x]=++tim;
	siz[x]=1;
	dep[x]=dep[fa[x][1]]+1;
	for(i=tai[x];i;i=mp[i].fro){
		y=mp[i].to;
		if(!siz[y]){
			for(j=1,t=x;t;j++){
				fa[y][j]=t;
				t=fa[t][j];
			}
			dfs(y);
			siz[x]+=siz[y];
		}
	}
}
int lca(int x,int y){
	int i;
	if(dep[x]<dep[y]){
		swap(x,y);
	}
	for(i=20;i;i--){
		if(dep[fa[x][i]]>=dep[y]){
			x=fa[x][i];
		}
	}
	for(i=20;i;i--){
		if(fa[x][i]!=fa[y][i]){
			x=fa[x][i];
			y=fa[y][i];
		}
	}
	return x==y?x:fa[x][1];
}
int dis(int x,int y){
	return dep[x]+dep[y]-2*dep[lca(x,y)];
}
int main(){
	/*
	freopen("data.txt","r",stdin);
	freopen("dui.txt","w",stdout); 
	//*/
	int i,x,y;
	scanf("%d%d%d",&n,&m,&s);
	for(i=1;i<n;i++){
		scanf("%d%d",&x,&y);
		bde(x,y);
	}
	dfs(s);
	scanf("%d",&x);
	ans+=dis(s,x);
	change(dfn[x]);
	change(dfn[s]);
	s=x;
	for(i=2;i<=m;i++){
		scanf("%d",&x);
		if(!(ask(dfn[x]+siz[x]-1)-ask(dfn[x]-1))){
			ans+=dis(s,x);
			s=x;
			change(dfn[x]);
		}
	}
	printf("%lld\n",ans);
	return 0;
}

/*
5 4 2 
1 2 
2 3 
3 4 
4 5 
4 3 1 5 

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值