Advertisement
Guest User

Farthest Node Problem-II LightOJ

a guest
Jan 18th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. //Bismillahir Rahmanir Rahim
  2.  
  3. #include<bits/stdc++.h>
  4.  
  5. #define output() freopen("out.txt","w",stdout)
  6. #define pii pair<int,long>
  7. #define MAX 30010
  8.  
  9. using namespace std;
  10.  
  11. vector<pii>edge[MAX];
  12. queue<long> q;
  13. vector<bool>visited;
  14. vector<long> dist;
  15.  
  16. long BFS(int s,int n){
  17.     q.push(s);
  18.  
  19.     for(int i=0;i<n;i++){
  20.         visited.push_back(false);
  21.         dist.push_back(0);
  22.     }
  23.  
  24.     visited[s]=true;
  25.     dist[s]=0;
  26.     long m=-1;
  27.     while(!q.empty()){
  28.         int top = q.front();
  29.  
  30.         int sz = edge[top].size();
  31.  
  32.         for(int i=0;i<sz;i++){
  33.             pii k= edge[top][i];
  34.             int a=k.first;
  35.             long w=k.second;
  36.  
  37.             if(!visited[a]){
  38.                 q.push(a);
  39.                 visited[a]=true;
  40.                 dist[a]=dist[top]+w;
  41.                 if(dist[a]>m){
  42.                     m=dist[a];
  43.                 }
  44.             }
  45.         }
  46.         q.pop();
  47.     }
  48.     if(!q.empty()){
  49.         queue<long> e;
  50.         swap(q,e);
  51.     }
  52.  
  53.     dist.clear();
  54.     visited.clear();
  55.  
  56.     return m;
  57. }
  58.  
  59.  
  60. int main(){
  61.     int test;
  62.     scanf("%d",&test);
  63.     int counter=1;
  64.     while(test--){
  65.         int n;
  66.         scanf("%d",&n);
  67.         for(int i=0;i<n-1;i++){
  68.             int s,d;
  69.             long w;
  70.             scanf("%d%d%ld",&s,&d,&w);
  71.             edge[s].push_back(pii(d,w));
  72.             edge[d].push_back(pii(s,w));
  73.         }
  74.  
  75.         printf("Case %d:\n",counter++);
  76.  
  77.         for(int i=0;i<n;i++){
  78.             long res= BFS(i,n);
  79.             printf("%ld\n",res);
  80.         }
  81.  
  82.         for(int i=0;i<n;i++) edge[i].clear();
  83.     }
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement