#include <utility>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <set>
#include <vector>
#include <cmath>
#include <queue>
#include <bitset>
#include <map>
#include <iterator>
using namespace std;
#define clr(a,v) memset(a,v,sizeof(a))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int INF = 0x7f7f7f7f;
const int maxn = 11111;
const int POW = 14;
const double eps = 1e-8;
const int mod = 777777777;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> pii;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<VVI> VVVI;
struct node {
int v, next, w;
node() {
}
node(int v, int next, int w) :
v(v), next(next), w(w) {
}
} edge[maxn << 3];
struct Query {
int v, next, id;
Query() {
}
Query(int v, int next, int id) :
v(v), next(next), id(id) {
}
} EDGE[2111111];
int Head[maxn << 1], head[maxn << 1], E, e;
void add_Query(int u, int v, int id) {
EDGE[E] = Query(v, Head[u], id);
Head[u] = E++;
}
void add_edge(int u, int v, int w) {
edge[e] = node(v, head[u], w);
head[u] = e++;
edge[e] = node(u, head[v], w);
head[v] = e++;
}
int dis[maxn];
int f[maxn], p[maxn];
bool vis[maxn];
int ans[2111111];
int find(int n, int f[]) {
return f[n] == n ? n : f[n] = find(f[n], f);
}
bool connect(int a, int b) {
int x = find(a, p);
int y = find(b, p);
return x == y;
}
void dfs(int u) {
vis[u] = true;
int i, v, id, lca;
for (i = Head[u]; ~i; i = EDGE[i].next) {
v = EDGE[i].v;
id = EDGE[i].id;
if (!connect(u, v)) {
ans[id >> 1] = -1;
continue;
}
if (vis[v]) {
lca = find(v, f);
ans[id >> 1] = dis[u] + dis[v] - dis[lca] * 2;
}
}
for (i = head[u]; ~i; i = edge[i].next) {
v = edge[i].v;
if (vis[v])
continue;
dis[v] = dis[u] + edge[i].w;
dfs(v);
f[v] = u;
}
}
int main() {
ios::sync_with_stdio(false);
int n, m, i, c, u, v, w;
while (~scanf("%d%d%d", &n, &m, &c)) {
E = e = 0;
memset(head, -1, sizeof(head));
memset(Head, -1, sizeof(Head));
memset(vis, false, sizeof(vis));
for (i = 1; i <= n; ++i)
f[i] = p[i] = i;
for (i = 0; i < m; ++i) {
scanf("%d%d%d", &u, &v, &w);
add_edge(u, v, w);
u = find(u, p);
v = find(v, p);
p[u] = v;
}
for (i = 0; i < c; ++i) {
scanf("%d%d", &u, &v);
add_Query(u, v, i << 1);
add_Query(v, u, i << 1 | 1);
}
for (i = 1; i <= n; ++i)
if (!vis[i]) {
dis[i] = 0;
dfs(i);
}
for (i = 0; i < c; ++i) {
if (~ans[i])
printf("%d\n", ans[i]);
else
printf("Not connected\n");
}
}
return 0l;
}
HDU Connections between cities
最新推荐文章于 2013-11-12 20:27:09 发布