码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 3195 Design the city

时间:2019-04-27 00:08:14      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:display   img   mes   clu   ase   targe   close   getchar   tin   

 

传送门

三个点之间的最短路径

答案就是两两lca之和除以2

注意输出格式。

技术图片
#include <bits/stdc++.h>
using namespace std;

inline int read() {
    int x = 0, f = 1; char ch = getchar();
    while (ch < 0 || ch > 9) { if (ch == -) f = -1; ch = getchar();}
    while (ch >= 0 && ch <= 9) { x = x * 10 + ch - 0; ch = getchar(); }
    return x * f;
}

const int maxn = 5e4 + 10;
const int maxm = 7e4 + 10;
struct Edge { int v, c, next; } edge[maxn * 2];
struct Qedge { int v, next, num, id; } qedge[maxm * 6];
int cnt, head[maxn], qcnt, qhead[maxn], dep[maxn];
int ans[maxm][4], n, m, par[maxn];
bool vis[maxn];

inline void addedge(int u, int v, int c) { 
    edge[++cnt].v = v; 
    edge[cnt].c = c; 
    edge[cnt].next = head[u]; 
    head[u] = cnt; 
}
inline void addqedge(int u, int v, int num, int id) { 
    qedge[++qcnt].v = v; 
    qedge[qcnt].next = qhead[u]; 
    qhead[u] = qcnt; 
    qedge[qcnt].num = num; 
    qedge[qcnt].id = id;
}
int getfa(int x) { return x == par[x] ? x : par[x] = getfa(par[x]); }
void dfs(int u) {
    vis[u] = 1;
    par[u] = u;
    for (int i = head[u]; i; i = edge[i].next) {
        int v = edge[i].v;
        if (vis[v]) continue;
        dep[v] = dep[u] + edge[i].c;
        dfs(v);
        par[v] = u;
    }
    for (int i = qhead[u]; i; i = qedge[i].next) {
        int v = qedge[i].v;
        if (vis[v]) {
            int x = getfa(v);
            ans[qedge[i].id][qedge[i].num] = dep[u] + dep[v] - 2 * dep[x];  
        }
    }
}

int main() {
    int kase = 0;
    while (~scanf("%d", &n)) {
        memset(head, 0, sizeof(head));
        memset(qhead, 0, sizeof(qhead));
        cnt = qcnt = 0;
        memset(ans, 0, sizeof(ans));
        memset(vis, 0, sizeof(vis));
        for (int i = 0; i < n - 1; i++) {
            int u = read(), v = read(), c = read();
            addedge(u, v, c);
            addedge(v, u, c);
        }
        m = read();
        for (int i = 0; i < m; i++) {
            int u = read(), v = read(), w = read();
            addqedge(u, v, 0, i); addqedge(v, u, 0, i);
            addqedge(v, w, 1, i); addqedge(w, v, 1, i);
            addqedge(u, w, 2, i); addqedge(w, u, 2, i);
        }
        dfs(0);
        if (kase) puts(""); kase++;
        for (int i = 0; i < m; i++) printf("%d\n", (ans[i][0] + ans[i][1] + ans[i][2]) / 2);
    }
    return 0;
}
View Code

 

ZOJ 3195 Design the city

标签:display   img   mes   clu   ase   targe   close   getchar   tin   

原文地址:https://www.cnblogs.com/Mrzdtz220/p/10777241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!