# bzoj4890 [Tjoi2017]城市 树形dp

1073 篇文章 0 订阅
40 篇文章 0 订阅

## Description

1 <= u,v <= n,1<= d <= 2000

1. 两棵树各自直径取max
2. 新加边连向两棵树的中心

## Code

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)

const int INF=0x3f3f3f3f;
const int N=5005;

struct edge {int x,y,w,next;} e[N*2];

int f1[N],f2[N],b1[N],b2[N];
int ls[N],len[2],edCnt=1;
int res,mx,now,opt;

std:: vector <int> vec,rec;

bool used[N*2];

int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}

void add_edge(int x,int y,int w) {
e[++edCnt]=(edge) {x,y,w,ls[x]}; ls[x]=edCnt;
e[++edCnt]=(edge) {y,x,w,ls[y]}; ls[y]=edCnt;
}

void upd(int &x,int v) {
(x<v)?(x=v):0;
}

void dfs1(int x,int fa) {
f1[x]=f2[x]=0;
for (int i=ls[x];i;i=e[i].next) {
if (e[i].y==fa||used[i]) continue;
dfs1(e[i].y,x);
if (f1[e[i].y]+e[i].w>f1[x]) {
f2[x]=f1[x]; b2[x]=b1[x];
f1[x]=f1[e[i].y]+e[i].w; b1[x]=e[i].y;
} else if (f1[e[i].y]+e[i].w>f2[x]) {
f2[x]=f1[e[i].y]+e[i].w; b2[x]=e[i].y;
}
}
upd(now,f1[x]+f2[x]);
}

void dfs2(int x,int fa) {
len[opt]=std:: min(len[opt],f1[x]);
for (int i=ls[x];i;i=e[i].next) {
if (e[i].y==fa||used[i]) continue;
int tmp;
if (b1[x]==e[i].y) tmp=f2[x]+e[i].w;
else tmp=f1[x]+e[i].w;
if (tmp>f1[e[i].y]) {
f2[e[i].y]=f1[e[i].y]; b2[e[i].y]=b1[e[i].y];
f1[e[i].y]=tmp; b1[e[i].y]=x;
} else if (tmp>f2[e[i].y]) {
f2[e[i].y]=tmp; b2[e[i].y]=x;
}
dfs2(e[i].y,x);
}
}

int dfs(int x,int fa,int dis) {
if (dis>mx) mx=dis,res=x,rec=vec;
for (int i=ls[x];i;i=e[i].next) {
if (e[i].y==fa||used[i]) continue;
vec.push_back(i);
dfs(e[i].y,x,dis+e[i].w);
vec.pop_back();
}
}

void clr(int n) {
rep(i,0,n) f1[i]=f2[i]=0;
}

int main(void) {
freopen("data.in","r",stdin);
rep(i,2,n) {
}
res=mx=0; dfs(1,0,0);
mx=0; dfs(res,0,0);
for (int i=0;i<rec.size();++i) {
used[rec[i]]=used[rec[i]^1]=1;
int x=e[rec[i]].x,y=e[rec[i]].y;
now=0; len[0]=len[1]=INF;
opt=0; dfs1(x,y); dfs2(x,y);
opt=1; dfs1(y,x); dfs2(y,x);
upd(now,e[rec[i]].w+len[0]+len[1]);

ans=std:: min(ans,now);
used[rec[i]]=used[rec[i]^1]=0;
}
printf("%d\n", ans);
return 0;
}

• 0
点赞
• 1
收藏
觉得还不错? 一键收藏
• 0
评论
04-18 308
06-21 113
03-28 72
04-17 406
11-28 90
07-14 153
01-31 335
08-07 227
07-12 487
08-23 114
05-12 6078
05-10 1073

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