zoukankan      html  css  js  c++  java
  • Cow Marathon POJ

    After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.
    Input

    * Lines 1.....: Same input format as "Navigation Nightmare".

    Output

    * Line 1: An integer giving the distance between the farthest pair of farms.

    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
    

    Hint

    The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52.
    题解:树的直径,固定的套路
     1 #include<cstdio>
     2 #include<cstring>
     3 #include<iostream>
     4 #include<algorithm> 
     5 using namespace std;
     6 
     7 const int maxn=6005;
     8     
     9 char S[2];
    10 int n,m,tot;
    11 int head[maxn],dp[maxn];
    12 
    13 struct node{
    14     int to,next,va;
    15 }e[maxn];
    16 
    17 void Inite(){
    18     tot=0;
    19     memset(head,-1,sizeof(head));
    20 }
    21 
    22 void addedge(int u,int v,int w){
    23     e[tot].to=v;
    24     e[tot].va=w;
    25     e[tot].next=head[u];
    26     head[u]=tot++;
    27 }
    28 
    29 void DFS(int pa,int u){
    30     for(int i=head[u];i!=-1;i=e[i].next){
    31         int v=e[i].to;
    32         if(pa==v) continue;
    33         dp[v]=dp[u]+e[i].va;
    34         DFS(u,v);
    35     }
    36 }
    37 
    38 int main()
    39 {   int temp;
    40     scanf("%d%d",&n,&m);
    41     
    42     Inite();
    43     while(m--){
    44         int a,b,c;
    45         scanf("%d%d%d%s",&a,&b,&c,S);
    46         addedge(a,b,c);
    47         addedge(b,a,c);
    48     }
    49     memset(dp,0,sizeof(dp));
    50     DFS(0,1);
    51 
    52     temp=0;
    53     for(int i=1;i<=n;i++) if(dp[temp]<dp[i]) temp=i;
    54 
    55     memset(dp,0,sizeof(dp));
    56     DFS(0,temp);
    57 
    58     temp=0; 
    59     for(int i=1;i<=n;i++) if(dp[temp]<dp[i]) temp=i;
    60 
    61     int ans=dp[temp];
    62     cout<<ans<<endl;        
    63 } 
  • 相关阅读:
    POJ1659:Frogs' Neighborhood(图论)
    POJ1659:Frogs' Neighborhood(图论)
    zzuli2504: 建国的签到活动二(dfs)
    zzuli2504: 建国的签到活动二(dfs)
    zzuli2506: 建勋的魔法学院
    zzuli2506: 建勋的魔法学院
    趣学算法:沟通无限校园网 (最小生成树)
    cocoapods的使用
    MJExtension的使用
    类别
  • 原文地址:https://www.cnblogs.com/zgglj-com/p/7748244.html
Copyright © 2011-2022 走看看