标签:and math graph color ane sam mat 技术 about
Computer HDU - 2196
InputInput file contains multiple test cases.In each case there is natural number N (N<=10000) in the first line, followed by (N-1) lines with descriptions of computers. i-th line contains two natural numbers - number of computer, to which i-th computer is connected and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input are separated by a space.OutputFor each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).Sample Input
5 1 1 2 1 3 1 1 1
Sample Output
3 2 3 4 4
题意:一棵树,问某一个点能够走的不重复点的最长的路径是多少;
思路:先随便找一个点跑一遍树的直径,然后直径的两头各跑一遍dfs
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<sstream> #include<cmath> #include<stack> #include<cstdlib> #include <vector> #include<queue> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 40010; struct Edge { int u,v,next,len; }edge[maxn]; int n; int tot; int head[maxn]; bool vis[maxn]; void addedge(int u,int v,int w) { edge[tot].u = u; edge[tot].v = v; edge[tot].len = w; edge[tot].next = head[u]; head[u] = tot++; } int dfs(int start,int d[]) { for(int i = 1;i <= n;i++) d[i] = INF; memset(vis,false,sizeof vis); d[start] = 0; vis[start] = true; queue<int>que; que.push(start); int maxx = 0; int pos; while(!que.empty()) { int p = que.front(); que.pop(); vis[p] = false;; if(maxx < d[p]) { maxx = d[p]; pos = p; } for(int i=head[p];i!=-1;i=edge[i].next) { int v = edge[i].v; if(d[v] > d[p] + edge[i].len) { d[v] = d[p] + edge[i].len; if(!vis[v]) { que.push(v); vis[v] = true; } } } } return pos; } int main() { while(~scanf("%d",&n)) { int d1[maxn],d2[maxn]; memset(head,-1,sizeof head); tot = 0; for(int u = 2;u <= n;u++) { int v,w; scanf("%d %d",&v,&w); addedge(u,v,w); addedge(v,u,w); } int st = dfs(1,d1); int en = dfs(st,d1); dfs(en,d2); for(int i=1;i<=n;i++) printf("%d\n",max(d1[i],d2[i])); } }
标签:and math graph color ane sam mat 技术 about
原文地址:https://www.cnblogs.com/smallhester/p/10310732.html