首页 技术 正文
技术 2022年11月8日
0 收藏 808 点赞 1,295 浏览 1361 个字

重点是求树的直径、半径。

参考这里

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int n, uu[5005], vv[5005], ww[5005], cnt, hea[5005], zui[5005], cii[5005], dis;
//zui means the longest chain, cii means the second longest chain, all for length
int son[5005], ans=0x3f3f3f3f;
bool vis[5005];
struct Edge{
int too, nxt, val;
}edge[10005];
void add_edge(int fro, int too, int val){
edge[++cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
hea[fro] = cnt;
}
void getD(int x){
vis[x] = true;
for(int i=hea[x]; i; i=edge[i].nxt){
int t=edge[i].too;
if(!vis[t]){
getD(t);
int tmpdis=zui[t]+edge[i].val;
if(tmpdis>zui[x]){
cii[x] = zui[x];
zui[x] = tmpdis;
son[x] = t;
}
else if(tmpdis>cii[x])cii[x] = tmpdis;
}
}
dis = max(dis, zui[x]+cii[x]);
}
void getR(int x, int fadis){
dis = min(dis, max(fadis, zui[x]));
vis[x] = false;
for(int i=hea[x]; i; i=edge[i].nxt){
int t=edge[i].too;
if(vis[t]){
if(t==son[x])getR(t, max(fadis+edge[i].val, edge[i].val+cii[x]));
elsegetR(t, max(fadis+edge[i].val, edge[i].val+zui[x]));
}
}
}
void clr(){
memset(zui, 0, sizeof(zui));
memset(cii, 0, sizeof(cii));
}
int main(){
cin>>n;
for(int i=1; i<n; i++){
scanf("%d %d %d", &uu[i], &vv[i], &ww[i]);
add_edge(uu[i], vv[i], ww[i]);
add_edge(vv[i], uu[i], ww[i]);
}
for(int i=1; i<n; i++){
clr();
int d1, d2, r1, r2;
vis[vv[i]] = true; getD(uu[i]); d1 = dis;
dis = 0; getD(vv[i]); d2 = dis;
dis = 0x3f3f3f3f;
vis[vv[i]] = false; getR(uu[i], 0); r1 = dis;
dis = 0x3f3f3f3f; getR(vv[i], 0); r2 = dis;
ans = min(ans, max(max(d1, d2), r1+r2+ww[i]));
}
cout<<ans<<endl;
return 0;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,083
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,558
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,407
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,180
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,817
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,900