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;
    }
  • 相关阅读:
    java利用freemarker导出world
    各种Java加密算法
    SM2的非对称加解密java工具类
    Mybatis分页插件--------Pagehelper
    JS实现浏览器打印、打印预览
    java大文件断点续传
    数字证书在web应用中实现登陆
    CA数字加密解密Demo
    使用数字证书进行签名和加密解密
    一个有趣的模拟光照的shader(类似法线贴图)
  • 原文地址:https://www.cnblogs.com/Accepting/p/11243661.html
Copyright © 2011-2022 走看看