POJ 1985 Cow Marathon(树的直径)
2016-02-12 14:49
393 查看
Description
给出一棵无向树,求树的直径
Input
第一行为两个整数n和m分别表示点数和边数,之后m行每行表示树的一条边
Output
输出树的直径长度
Sample Input
7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
Sample Output
52
Solution
树的直径裸题
Code
给出一棵无向树,求树的直径
Input
第一行为两个整数n和m分别表示点数和边数,之后m行每行表示树的一条边
Output
输出树的直径长度
Sample Input
7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
Sample Output
52
Solution
树的直径裸题
Code
#include<cstdio> #include<iostream> #include<cstring> #include<queue> using namespace std; #define maxn 111111 struct node { int to,c,next; }edge[2*maxn]; int n,m,head[maxn],tot,dis[maxn],vis[maxn]; void init() { memset(head,-1,sizeof(head)); tot=0; } void add(int u,int v,int c) { edge[tot].to=v; edge[tot].c=c; edge[tot].next=head[u]; head[u]=tot++; } void dfs(int u) { for(int i=head[u];~i;i=edge[i].next) { int v=edge[i].to,c=edge[i].c; if(!vis[v]) { vis[v]=1; dis[v]=dis[u]+c; dfs(v); } } } int main() { int u,v,c,s;char op[3]; while(~scanf("%d%d",&n,&m)) { init(); while(m--) { scanf("%d%d%d%s",&u,&v,&c,op); add(u,v,c),add(v,u,c); } memset(vis,0,sizeof(vis)); dis[1]=0,vis[1]=1; dfs(1); for(int i=2,temp=-1;i<=n;i++) if(dis[i]>temp)temp=dis[i],s=i; memset(vis,0,sizeof(vis)); dis[s]=0,vis[s]=1; dfs(s); int ans=-1; for(int i=1;i<=n;i++) ans=max(ans,dis[i]); printf("%d\n",ans); } return 0; }
相关文章推荐
- spring(AOP)多个切面
- Educational Codeforces Round 7 B. The Time 水题
- BZOJ 3672: [Noi2014]购票( 树链剖分 + 线段树 + 凸包 )
- uvaoj-1225:数数字
- 关于Windows7 64的注册表读写问题
- Building Maintainable Software-java篇之Write Simple Units of Code
- sdptool 设备服务查找命令使用
- 汇编软件MASM和调试工具DEBUG的使用
- java基础20递归
- POJ 2631 Roads in the North(树的直径)
- Volley学习记录(二)
- mongodb分片部署
- 解决ADB端口占用问题
- Soket转发消息服务(群聊)
- 那些被吹的神乎其乎的QQ营销大法
- jquery封装之--css封装
- POJ 1015
- hdoj 2055 An easy problem
- linux系统常用命令-整理
- 如何找到理想的另一半?