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;
    }
  • 相关阅读:
    仅此一文让你明白ASP.NET MVC 之View的显示
    仅此一文让你明白ASP.NET MVC原理
    MVC4相关Razor语法以及Form表单
    关于jQuery UI 使用心得及技巧
    jQuery编程的最佳实践
    前端不为人知的一面--前端冷知识集锦
    jQuery插件开发精品教程,让你的jQuery提升一个台阶
    常用数据结构及复杂度
    初探12306售票算法
    ajax省市县三级联动
  • 原文地址:https://www.cnblogs.com/Accepting/p/11243661.html
Copyright © 2011-2022 走看看