比赛 |
ZLXOI2015Day2 |
评测结果 |
AAAAAAAAAA |
题目名称 |
ZLX的陨落 |
最终得分 |
100 |
用户昵称 |
dashgua |
运行时间 |
0.431 s |
代码语言 |
C++ |
内存使用 |
11.00 MiB |
提交时间 |
2015-10-30 19:57:35 |
显示代码纯文本
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
template<class Num>void read(Num &x)
{
char c; int flag = 1;
while((c = getchar()) < '0' || c > '9')
if(c == '-') flag *= -1;
x = c - '0';
while((c = getchar()) >= '0' && c <= '9')
x = (x<<3) + (x<<1) + (c-'0');
x *= flag;
return;
}
template<class Num>void write(Num x)
{
if(!x) {putchar('0');return;}
if(x < 0) putchar('-'), x = -x;
static char s[20];int sl = 0;
while(x) s[sl++] = x%10 + '0',x /= 10;
while(sl) putchar(s[--sl]);
}
const int maxn = 1e5 + 20, logN = 18;
struct Edge
{
int v, w, next;
Edge(int v = 0,int w = 0,int next = 0):v(v), w(w), next(next){}
}edge[maxn << 1];
int N, M;
int head[maxn], el;
int fa[maxn][logN], dep[maxn];
long long dist[maxn];
void newedge(int u,int v,int w)
{
edge[++el] = Edge(v, w, head[u]), head[u] = el;
}
void init()
{
int u, v, w;
read(N), read(M);
for(int i = 1; i <= M; i++)
{
read(u), read(v), read(w);
newedge(u, v, w), newedge(v, u, w);
}
}
void dfs(int a)
{
dep[a] = dep[fa[a][0]] + 1;
for(int i = 1; i < logN; i++)
fa[a][i] = fa[fa[a][i - 1]][i - 1];
for(int i = head[a]; i ; i = edge[i].next)
{
int p = edge[i].v;
if(p != fa[a][0])
{
dist[p] = dist[a] + edge[i].w;
fa[p][0] = a, dfs(p);
}
}
}
int getlca(int u,int v)
{
if(dep[u] > dep[v]) std::swap(u, v);
for(int i = logN - 1; i >= 0; i--)
if(dep[fa[v][i]] >= dep[u]) v = fa[v][i];
if(u == v) return u;
for(int i = logN - 1; i >= 0; i--)
if(fa[u][i] != fa[v][i]) u = fa[u][i], v = fa[v][i];
return fa[u][0];
}
void solve()
{
int Q, u, v, lca;
read(Q);
while(Q--)
{
read(u), read(v), lca = getlca(u, v);
write(dist[u] + dist[v] - (dist[lca] << 1)), puts("");
}
}
int main()
{
freopen("ThefallingofZLX.in","r",stdin);
freopen("ThefallingofZLX.out","w",stdout);
init();
dfs(1);
solve();
fclose(stdin);
fclose(stdout);
return 0;
}