ZOJ 3195 Design the city LCA

题目:http://www.icpc.moe/onlinejudge/showProblem.do?problemCode=3195


题意:给定一个树,求三点之间的距离


思路:假定三点为u, v, w,那么(dist[u,v] + dist[v,w] + dist[u,w]) / 2就是答案


总结:wa时不要灰心,也许你离ac不远了

#include
#include
#include
#include
using namespace std;

const int N = 50010;
struct edge1
{
    int to, cost, next;
} g1[N*2];
struct edge2
{
    int to, ind, next;
} g2[N*10];
int head1[N], head2[N], dist[N], res[N*10], par[N];
int cnt1, cnt2;
bool vis[N];
int n, m;
void init()
{
    for(int i = 0; i < n; i++)
        par[i] = i;
    memset(head1, -1, sizeof head1);
    memset(head2, -1, sizeof head2);
    memset(vis, 0, sizeof vis);
    cnt1 = cnt2 = 0;
}
void add_edge1(int v, int u, int c)
{
    g1[cnt1].to = u;
    g1[cnt1].cost = c;
    g1[cnt1].next = head1[v];
    head1[v] = cnt1++;
}
void add_edge2(int v, int u, int ind)
{
    g2[cnt2].to = u;
    g2[cnt2].ind = ind;
    g2[cnt2].next = head2[v];
    head2[v] = cnt2++;
}
int ser(int v)
{
    int r = v, i = v, j;
    while(r != par[r]) r = par[r];
    while(i != r) j = par[i], par[i] = r, i = j;
    return r;
}
void tarjan_lca(int v)
{
    vis[v] = true;
    int u;
    for(int i = head1[v]; i != -1; i = g1[i].next)
        if(!vis[u=g1[i].to])
        {
            dist[u] = dist[v] + g1[i].cost;
            tarjan_lca(u);
            par[u] = v;
        }
    for(int i = head2[v]; i != -1; i = g2[i].next)
        if(vis[u=g2[i].to])
            res[g2[i].ind] = dist[v] + dist[u] - 2 * dist[ser(u)];
}
int main()
{
    int a, b, c, x = 0;
    while(~ scanf("%d", &n))
    {
        init();
        for(int i = 0; i < n - 1; i++)
        {
            scanf("%d%d%d", &a, &b, &c);
            add_edge1(a, b, c);
            add_edge1(b, a, c);
        }
        scanf("%d", &m);
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d%d", &a, &b, &c);
            add_edge2(a, b, i);
            add_edge2(b, a, i);
            add_edge2(b, c, i + m);
            add_edge2(c, b, i + m);
            add_edge2(a, c, i + 2 * m);
            add_edge2(c, a, i + 2 * m);
        }
        dist[0] = 0;
        tarjan_lca(0);
        if(x++) printf("\n");
        for(int i = 0; i < m; i++)
            printf("%d\n", (res[i] + res[i+m] + res[i+2*m]) / 2);
    }
    return 0;
}


你可能感兴趣的:(acm,zoj,LCA,tarjan,LCA)