HDU 2874(LCA)

来源:互联网 发布:网络作答系统网站 编辑:程序博客网 时间:2024/06/10 08:10
/*题意:给定一张图,包括n个城市,m条路径,q个询问( 图中没有环 )。LCA问题:询问a,b的最短距离.则:ans = dis[a] + dis[b] - dis[father]*2;*/#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <cmath>#include <queue>#include <vector>using namespace std;typedef long long LL;const int maxn = 10007;int n, m, c, num;int deep[maxn], dis[maxn], pa[maxn], head[maxn]; ///pa[]表示父亲节点int ace[maxn]; ///最近公共祖先struct Node{    int from, to, val, Next;}edge[maxn<<2];void init() {    memset(head, -1, sizeof(head));    num = 0;    memset(pa, 0, sizeof(pa));}void addedge(int a, int b, int c) {    edge[num].from = a;    edge[num].to = b;    edge[num].val = c;    edge[num].Next = head[a];    head[a] = num++;}int Find(int x, int y) {    if(x == y) return x;    if(deep[x] > deep[y]) return Find(pa[x], y);    else return Find(x, pa[y]);}void dfs(int now, int paa, int acee, int deepp, int diss) {    pa[now] = paa;    deep[now] = deepp;    dis[now] = diss;    ace[now] = acee;    for(int i = head[now]; i != -1; i = edge[i].Next) {        int v = edge[i].to;        if(pa[v] == 0) dfs(v, now, acee, deepp+1, diss+edge[i].val);        ///pa==0,因为是无向图。这只是求距离,对父子关系要求不明显    }}int main() {//    freopen("in.txt", "r", stdin);    while(~scanf("%d%d%d", &n, &m, &c)) {        init();        for(int i = 0; i < m; ++i) {            int t1, t2, t3; scanf("%d%d%d", &t1, &t2, &t3);            addedge(t1, t2, t3);            addedge(t2, t1, t3);        }        for(int i = 1; i <= n; ++i) {            if(pa[i] == 0) {                dfs(i, -1, i, 0, 1);            }        }        for(int i = 0; i < c; ++i) {            int t1, t2; scanf("%d%d", &t1, &t2);            if(ace[t1] == ace[t2]) {                int paa = Find(t1, t2);                printf("%d\n", dis[t1]+dis[t2]-2*dis[paa]);            }            else printf("Not connected\n");        }    }}

0 0