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