zoukankan      html  css  js  c++  java
  • E

    Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.

    Input

    Input starts with an integer T (≤ 10), denoting the number of test cases.

    Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1 lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000)denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.

    Output

    For each case, print the case number and the maximum distance.

    Sample Input

    2

    4

    0 1 20

    1 2 30

    2 3 50

    5

    0 2 20

    2 1 10

    0 3 29

    0 4 50

    Sample Output

    Case 1: 100

    Case 2: 80

    题目大意:输入A,B,点以及a点b点之间的距离输出,,两点最远的距离

    AC代码:

    #include<cstdio>
    #include<vector>
    #include<iostream>
    #include<cstring>
    using namespace std;
    struct stu{
        int y,s;
    };
    vector<stu>ve[30010];
    int ans=0; 
    int xx;
    int mark[30010];
    void dfs(int x,int step){
        if(step>ans){
            ans=step;
            xx=x;
        }
        for(int i=0;i<ve[x].size();i++){
            if(mark[ve[x][i].y]==0){
                mark[ve[x][i].y]=1;
                dfs(ve[x][i].y,step+ve[x][i].s);
                mark[ve[x][i].y]=0;
            }
        }
    }
    int main()
    {
        int t;
        scanf("%d",&t);
        for(int j=1;j<=t;j++){
            int a,b,c,n;
            ans=0;
            scanf("%d",&n);
            
            for(int i=0;i<n-1;i++){
                scanf("%d %d %d",&a,&b,&c);
                ve[a].push_back({b,c});
                ve[b].push_back({a,c});
            }
            
            memset(mark,0,sizeof(mark));
            mark[1]=1;
            dfs(1,0);
            memset(mark,0,sizeof(mark));
            mark[xx]=1;
            dfs(xx,0);
            printf("Case %d: %d
    ",j,ans);
            for(int i=0;i<n;i++){
                ve[i].clear();
            }
        }
        return 0;
    }
  • 相关阅读:
    WSS 3.0和MOSS 中的Web Parts
    WSS3.0 和 MOSS 的版本号小结
    设置firefox的默认google搜索.com而不是.hk
    wcf web service遇到"Could not load file or assembly App_Web..."问题
    ASP .NET readonly texbox 后台不能读取问题的解决办法
    2009年底泰国游总结
    把Silverlight的WCF service配置地址放到web.config中
    gvim编辑xml更新
    法意蜜月之旅总结
    法意蜜月之旅签证、交通、酒店篇
  • 原文地址:https://www.cnblogs.com/Accepting/p/11243661.html
Copyright © 2011-2022 走看看