您的位置:首页 > 其它

BZOJ3732 Network

2014-12-13 10:02 260 查看
这貌似是13年的noip最后一道吧?、、、

蒟蒻只会这种题呢、、、

Kruskal求出MST,然后倍增就好了

/**************************************************************
Problem: 3732
User: rausen
Language: C++
Result: Accepted
Time:268 ms
Memory:4412 kb
****************************************************************/

#include <cstdio>
#include <algorithm>

using namespace std;
const int N = 16005;
const int M = 30005;

struct Edge {
int x, y, v;

inline bool operator < (const Edge &x) const {
return v < x.v;
}
} E[M];

struct edge {
int next, to, v;
edge() {}
edge(int _n, int _t, int _v) : next(_n), to(_t), v(_v) {}
} e[M];

struct tree_node {
int fa[16], mx[16], dep;
} tr
;

int n, m;
int fa
;
int tot, first
;

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

inline void Add_Edges(int x, int y, int v) {
e[++tot] = edge(first[x], y, v), first[x] = tot;
e[++tot] = edge(first[y], x, v), first[y] = tot;
}

int find_fa(int x) {
return x == fa[x] ? x : fa[x] = find_fa(fa[x]);
}

void Kruskal() {
int i, cnt, fa1, fa2;
sort(E + 1, E + m + 1);
for (i = 1; i <= n; ++i)
fa[i] = i;
for (i = 1, cnt = 0; i <= m; ++i) {
fa1 = find_fa(E[i].x), fa2 = find_fa(E[i].y);
if (fa1 != fa2) {
fa[fa1] = fa2, ++cnt;
Add_Edges(E[i].x, E[i].y, E[i].v);
if (cnt == n - 1) break;
}
}
}

void dfs(int p) {
int x, y;
for (x = 1; x < 16; ++x) {
tr[p].fa[x] = tr[tr[p].fa[x - 1]].fa[x - 1];
tr[p].mx[x] = max(tr[p].mx[x - 1], tr[tr[p].fa[x - 1]].mx[x - 1]);
}
for (x = first[p]; x; x = e[x].next)
if ((y = e[x].to) != tr[p].fa[0]) {
tr[y].dep = tr[p].dep + 1;
tr[y].fa[0] = p, tr[y].mx[0] = e[x].v;
dfs(y);
}
}

int query(int x, int y) {
int res = 0, i;
if (tr[x].dep < tr[y].dep) swap(x, y);
for (i = 15; ~i; --i)
if (tr[tr[x].fa[i]].dep >= tr[y].dep) {
res = max(res, tr[x].mx[i]);
x = tr[x].fa[i];
}
for (i = 15; ~i; --i)
if (tr[x].fa[i] != tr[y].fa[i]) {
res = max(res, max(tr[x].mx[i], tr[y].mx[i]));
x = tr[x].fa[i], y = tr[y].fa[i];
}
if (x != y)
res = max(res, max(tr[x].mx[0], tr[y].mx[0]));
return res;
}

int main() {
n = read(), m = read();
int Q = read(), i, x, y;
for (i = 1; i <= m; ++i)
E[i].x = read(), E[i].y = read(), E[i].v = read();
Kruskal();
tr[1].dep = 1;
dfs(1);
while (Q--) {
x = read(), y = read();
printf("%d\n", query(x, y));
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: