bzoj3743 Kamp bfs

       总感觉好像在哪里做过。。

       假设每次都要回到原点。那么对于人形成的一个树(下面的树,都指这棵树),显然每条边都要来回走一遍。对于一个点i,如果不在树上,还要求出它走到最近的树上点的距离再*2。但是这道题目不需要回到原点,因此我们让它少走的距离最大,即要求出它到树上点最长的距离。可以用反正法得到到树上最长的距离一定是到树的直径的两个端点中的一个。

       于是就四个bfs解决了。。

AC代码如下(写得好慢):

#include<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
#define N 1000005
using namespace std;

int n,m,tot,cnt,fst[N],pnt[N],len[N],nxt[N],last[N],f[N],h[N],val[N]; ll d[3][N]; bool bo[N];
int read(){
	int x=0; char ch=getchar();
	while (ch<'0' || ch>'9') ch=getchar();
	while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); }
	return x;
}
void add(int aa,int bb,int cc){
	pnt[++tot]=bb; len[tot]=cc; nxt[tot]=fst[aa]; fst[aa]=tot;
}
void bfs(int k,int now){
	int head=0,tail=now,i; memset(d[k],-1,sizeof(d[k]));
	for (i=1; i<=tail; i++) d[k][h[i]]=0;
	while (head<tail){
		int x=h[++head],p;
		for (p=fst[x]; p; p=nxt[p]){
			int y=pnt[p];
			if (d[k][y]==-1){
				d[k][y]=d[k][x]+len[p]; h[++tail]=y; last[y]=x; val[y]=len[p];
			}
		}
	}
}
int main(){
	n=read(); m=read(); int i,j,k=1; ll sum=0;
	for (i=1; i<n; i++){
		int x=read(),y=read(),z=read();
		add(x,y,z); add(y,x,z);
	}
	for (i=1; i<=m; i++) f[i]=read();
	h[1]=f[1]; bfs(0,1); bo[f[1]]=1;
	for (i=2; i<=m; i++){
		if (d[0][f[i]]>d[0][f[k]]) k=i;
		for (j=f[i]; j!=f[1] && !bo[j]; j=last[j]){ sum+=val[j]; bo[j]=1; }
	}
	//for (i=1; i<=n; i++) if (bo[i]) cout<<i<<' '; puts("");
		//for (i=1; i<=n; i++) cout<<d[0][i]<<' '; puts("");
	for (i=1; i<=n; i++) if (bo[i]) h[++cnt]=i; bfs(0,cnt);
	h[1]=f[k]; bfs(1,1); k=1;
	for (i=2; i<=m; i++) if (d[1][f[i]]>d[1][f[k]]) k=i;
	h[1]=f[k]; bfs(2,1); sum<<=1;
	//for (i=1; i<=n; i++) cout<<d[0][i]<<' '<<d[1][i]<<' '<<d[2][i]<<endl;
	for (i=1; i<=n; i++) printf("%lld\n",bo[i]?sum-max(d[1][i],d[2][i]):sum+(d[0][i]<<1)-max(d[1][i],d[2][i]));
	return 0;
}

by lych

2016.2.4

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值