Advertisement
aurko96

Lightoj-1094_dfs

Nov 21st, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define LL long long
  3. using namespace std;
  4. vector<pair<LL,LL> >edge[30005];
  5. LL dis[30008];
  6. bool vis[30005];
  7. void dfs(LL node,LL pre,LL unit)
  8. {
  9.     if(dis[node]>unit) dis[node]=unit;
  10.     else return;
  11.     for(int i=0;i<edge[node].size();i++)
  12.     {
  13.         int x=edge[node][i].first;
  14.         int y=edge[node][i].second;
  15.         if(x==pre) continue;
  16.         dfs(x,node,unit+y);
  17.     }
  18. }
  19. int main()
  20. {
  21.     LL i,j,n,x,y,z,t,p,q,r,s,ans;
  22.     scanf("%lld",&t);
  23.     for(i=1;i<=t;i++)
  24.     {
  25.         scanf("%lld",&n);
  26.         for(j=0;j<n;j++) edge[j].clear();
  27.         for(j=0;j<n-1;j++)
  28.         {
  29.             scanf("%lld %lld %lld",&x,&y,&z);
  30.             edge[x].push_back(make_pair(y,z));
  31.             edge[y].push_back(make_pair(x,z));
  32.         }
  33.         for(j=0;j<=30005;j++) dis[j]=1000000000;
  34.         dfs(0,-1,0);
  35.         r=*max_element(dis,dis+n);
  36.         for(j=0,p=0,q=0;j<n;j++)
  37.         {
  38.             if(p<dis[j])
  39.             {
  40.                 p=dis[j];
  41.                 q=j;
  42.             }
  43.         }
  44.         for(j=0;j<=30005;j++) dis[j]=1000000000;
  45.         dfs(q,-1,0);
  46.         s=*max_element(dis,dis+n);
  47.         ans=max(r,s);
  48.         printf("Case %lld: %lld\n",i,ans);
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement