【poj Roads in the North】 题解
2024-08-28 04:55:17
题目链接:http://poj.org/problem?id=2631
求树的直径模板。
定理:
树上任意一个点的在树上的最长路一定以树的直径的两端点其中一点结束。
做法:
两边bfs,第一次先找到node(树的直径的两端点其中一个),再一次求node的最长路所结束的点t
node—>t就是树的直径
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100010;
int n, dis[maxn], ans, node;
bool vis[maxn];
struct edge{
int from, to, next, len;
}e[maxn<<2];
int cnt, head[maxn];
void add(int u, int v, int w)
{
e[++cnt].from = u;
e[cnt].next = head[u];
e[cnt].len = w;
e[cnt].to = v;
head[u] = cnt;
}
queue<int> q;
void bfs(int s)
{
vis[s] = 1;
q.push(s);
while(!q.empty())
{
int now = q.front(); q.pop();
for(int i = head[now]; i != -1; i = e[i].next)
{
if(vis[e[i].to] == 0)
{
dis[e[i].to] = dis[now] + e[i].len;
vis[e[i].to] = 1;
q.push(e[i].to);
if(dis[e[i].to] > ans)
{
ans = dis[e[i].to];
node = e[i].to;
}
}
}
}
}
int main()
{
memset(head, -1, sizeof(head));
int u, v, w;
while(scanf("%d%d%d",&u, &v, &w) == 3)
{
add(u, v, w);
add(v, u, w);
}
memset(dis, 0, sizeof(dis));
memset(vis, 0, sizeof(vis));
ans = 0;
bfs(1);
memset(vis, 0, sizeof(vis));
dis[node] = 0;
ans = 0;
bfs(node);
printf("%d\n", ans);
return 0;
}
//Misaka_Azusa
//dsbdsb
最新文章
- POJ2417 Discrete Logging
- memcache原理、简单使用、分布式实现方案
- 机器数据的价值 - Web 访问日志和数据库审计日志
- luogu[1279]字串距离
- Inode详解-重要
- Laravel教程 五:MVC的基本流程
- 发生了COMException 异常来自 HRESULT:0x80040228
- ios 工程图片清理shell
- CentOS系统中常用查看日志命令
- Jqgrid动态拖拽
- C++的for循环细节,必看!
- MyEclipse使用总结——MyEclipse文件查找技巧
- 测试指南(适用于Feature/promotion/bug)
- c# Mongodb两个字段不相等 MongoDB原生查询
- LODOP中预览界面查看打印机的可打区域具体值
- Java基础4-面向对象概述;super();this()
- Robot FrameWork使用中常见问题收集
- ASP.NET Core 1.0 中使用 Log 日志配置
- codeforces 1133E K Balanced Teams
- Windows下安装Redmine 2.5.2不全然指南
热门文章
- [android] 切换界面的通用处理
- Spring Cloud个组件原理
- zookeeper【4】master选举
- Python基础-小程序练习(跳出多层循环,购物车,多级菜单,用户登录)
- EF单实对应多表
- 跳过图片反盗链js
- Oracle案例03——RMAN-06091: no channel allocated for maintenance (of an appropriate type)
- 解决maven工程无法创建src/main/java包名的方法
- SQL 查询:查询学生平均成绩
- Mysql学习---视图/触发器/存储过程/函数/执行计划/sql优化 180101