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的webpart的3种开发方式(转载)
    C# 2.0学习之集合2
    对C#中的TreeView添加背景图转载
    ASP.NET 2.0: 页面中链入的CSS、js文件带中文时需注意
    C# 2.0学习之泛型
    C# 2.0学习之数组
    连接 ACCESS 2007
    C# 2.0学习之事件2
    一个P2P+搜索音乐网站的策划书(转载)
    关于MOSS的应用和开发的一些联接
  • 原文地址:https://www.cnblogs.com/Accepting/p/11243661.html
Copyright © 2011-2022 走看看