https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1737

求出树的重心,跑spfa

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string> using namespace std;
const int N = 1e5 + ; #define oo 999999999999
#define yxy getchar() int n, now, Point, Min_siz;
int head[N] ,siz[N], Que[N << ];
struct Node {int v, w, nxt;} G[N << ];
bool vis[N];
long long dis[N]; inline int read(){
int x = ; char c = yxy;
while(c < '' || c > '') c = yxy;
while(c >= '' && c <= '') x = x * + c - '', c = yxy;
return x;
} inline void add(int u, int v, int w){
G[now].v = v; G[now].w = w; G[now].nxt = head[u]; head[u] = now ++;
} void dfs(int u, int father){
siz[u] = ;
int Max_son = -;
for(int i = head[u]; ~ i; i = G[i].nxt){
int v = G[i].v;
if(v != father){
dfs(v, u);
siz[u] += siz[v];
Max_son = max(Max_son, siz[v]);
}
}
Max_son = max(Max_son, n - siz[u]);
if(Max_son < Min_siz){
Min_siz = Max_son;
Point = u;
}
} void spfa(int S){
for(int i = ; i <= n; i ++) dis[i] = oo;
dis[S] = ;
int H = , T = ;
Que[H] = S;
while(H <= T){
int topp = Que[H ++];
vis[topp] = ;
for(int i = head[topp]; ~ i; i = G[i].nxt){
int v = G[i].v;
if(dis[v] > dis[topp] + G[i].w){
dis[v] = dis[topp] + G[i].w;
if(!vis[v]) vis[v] = , Que[++ T] = v;
}
}
}
} int main()
{
n = read();
for(int i = ; i <= n; i ++) head[i] = -;
for(int i = ; i < n; i ++) {
int u = read(), v = read(), w = read();
add(u, v, w); add(v, u, w);
}
Min_siz = ;
dfs(, );
spfa(Point);
long long Answer = ;
for(int i = ; i <= n; i ++) Answer += dis[i];
cout << Answer;
return ;
}

最新文章

  1. canvas初探3:画方画圆
  2. 深圳浩瀚技术有限公司(haohantech)推出的无线移动批发管理PDA解决方案------无线移动POS销售开单系统
  3. JSP九大内置对象详细介绍
  4. 在使用 百度编辑器 Ueditor 时,不能进入 Controller 相应的 Action 的处理方法
  5. 函数flst_get_last
  6. MyBatis Tutorial – CRUD Operations and Mapping Relationships – Part 1---- reference
  7. hive left outer join的问题
  8. 分享自制的C#和VB Code互转工具
  9. SQL SERVER 审核
  10. Spring学习日志之Spring Security配置
  11. luoguP1131
  12. React native 中使用Fetch请求数据
  13. HDFS笔记(二)
  14. django网页分页
  15. parallels Desktop解决无法压缩硬盘的问题
  16. Team Dipper
  17. 读取excel思路
  18. 修改别人写的Hibernate数据库操作代码
  19. linux arm mmu基础【转】
  20. Swing中如何比较好的判断鼠标左键双击

热门文章

  1. 使用HSE配置系统时钟并用MCO输出监测系统时钟
  2. element-ui获取用户选中项
  3. STM32之ADC实例(基于DMA方式)
  4. spring整合quartz框架
  5. (七)freemarker的基本语法及入门基础
  6. Visual Studio 2017修改编码UTF-8
  7. java封装数据类型——Integer
  8. React实现顶部固定滑动式导航栏(导航条下拉一定像素时显示原导航栏样式)
  9. Linux Centos7配置ftp服务器
  10. 结对编程作业(python实现)