light oj 1094(初学邻接表)

来源:互联网 发布:c语言经典程序 编辑:程序博客网 时间:2024/06/07 16:37

Farthest Nodes in a Tree
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu
Submit

Status
Description
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

题意:给你树的顶点数 N , 和N-1 条边,问你哪两条边最短
题解:树的直径的模板题,套进去就成了

#include <stdio.h>#include <string.h>#include <queue>using namespace std;#define M 100010int n, head[M], edgenum, s;struct node{    int from, to, val, next;};node edge[M*2];void getmap(int u, int v, int val)//要注意这个图是从后向前找的 {    node e = {u, v, val, head[u]};//记录前一个的尾部 -1使最后的节点     edge[edgenum] = e;// 记录在第edgenum里面 方便由head[u]追寻     head[u] = edgenum++;//head[u] 随着 edgenum 而动 记录指向的位置 使得通过 next 可以寻找到上一个点 }void init(){    edgenum = 0;    memset(head, -1, sizeof(head));}int dist[M], ans;bool vis[M];void bfs(int a){    memset(dist, 0, sizeof(dist));    memset(vis, false, sizeof(vis));    vis[a] = true;    ans = 0;    queue<int> q;    q.push(a);    while(!q.empty())    {        a = q.front();//计算以 a 为起点的最长边         q.pop();        for(int i=head[a]; i != -1; i = edge[i].next)//取出 a 指向的另一个目标         {            node e = edge[i];            if(!vis[e.to] && dist[e.to] < dist[a] + e.val)//因为求最长的边 所以不会向短的方向走             {                dist[e.to] = dist[a] + e.val;//给指向的赋值                 vis[e.to] = true;//用过的标记,免得又找回来                 if(dist[e.to] > ans)                {                    ans = dist[e.to];                    s = e.to;                }                q.push(e.to);//传递             }        }    }}int main(){    int t, a, b, c;    scanf("%d", &t);    for(int ca = 1; ca<=t; ca++)    {        scanf("%d", &n);        init();        for(int i=0; i<n-1; i++)        {            scanf("%d%d%d", &a, &b, &c);            getmap(a, b, c);            getmap(b, a, c);        }        s = 0;        bfs(0);        bfs(s);        printf("Case %d: %d\n", ca, ans);    }    return 0;}
0 0
原创粉丝点击