D - Connections between cities HDU - 2874
After World War X, a lot of cities have been seriously damaged, and we need to rebuild those cities. However, some materials needed can only be produced in certain places. So we need to transport these materials from city to city. For most of roads had been totally destroyed during the war, there might be no path between two cities, no circle exists as well.
Now, your task comes. After giving you the condition of the roads, we want to know if there exists a path between any two cities. If the answer is yes, output the shortest path between them.
Input
Input consists of multiple problem instances.For each instance, first line contains three integers n, m and c, 2<=n<=10000, 0<=m<10000, 1<=c<=1000000. n represents the number of cities numbered from 1 to n. Following m lines, each line has three integers i, j and k, represent a road between city i and city j, with length k. Last c lines, two integers i, j each line, indicates a query of city i and city j.
Output
For each problem instance, one line for each query. If no path between two cities, output “Not connected”, otherwise output the length of the shortest path between them.
Sample Input
5 3 2 1 3 2 2 4 3 5 2 3 1 4 4 5
Sample Output
Not connected 6
Hint
Hint Huge input, scanf recommended.
n个点,m条边,q次查询
跟之前题目不同的是可能会出现好多棵树
所以并查集先维护每个点属于哪棵树(vis数组为0时找)
然后正常的lca
#include <bits/stdc++.h>
using namespace std;
const int maxn=10005;
struct node
{
int v,w;
node(int vv,int ww)
{
v=vv,w=ww;
}
};
vector <node> g[maxn];
int dis[maxn],dep[maxn],vis[maxn],f[maxn][21];
int pre[maxn],n,m,q;
void init()
{
for(int i=1; i<=n; i++)
{
pre[i]=i;
g[i].clear();
}
memset(dis,0,sizeof(dis));
memset(dep,0,sizeof(dep));
memset(vis,0,sizeof(vis));
memset(f,0,sizeof(f));
}
int finding(int x)
{
if(pre[x]==x) return x;
return pre[x]=finding(pre[x]);
}
void unit(int x,int y)
{
int fx=finding(x),fy=finding(y);
if(fx!=fy) pre[fx]=fy;
}
void dfs(int u,int fa,int deep)
{
vis[u]=1;
f[u][0]=fa;
dep[u]=deep;
for(int i=0; i<g[u].size(); i++)
{
int v=g[u][i].v;
if(v==fa||vis[v]) continue;
dis[v]=dis[u]+g[u][i].w;
dfs(v,u,deep+1);
}
}
void init_lca()
{
for(int i=1; i<=n; i++)
{
if(!vis[i])
{
dis[i]=0;
dfs(i,-1,0);
}
}
for(int j=1; (1<<j)<=n; j++)
{
for(int i=1; i<=n; i++)
{
f[i][j]=f[f[i][j-1]][j-1];
}
}
}
int lca(int a,int b)
{
if(dep[a]<dep[b]) swap(a,b);
int d=dep[a]-dep[b];
for(int i=0; (1<<i)<=d; i++)
{
if((1<<i)&d) a=f[a][i];
}
if(a==b) return a;
for(int i=20; i>=0; i--)
{
if(f[a][i]!=f[b][i])
{
a=f[a][i];
b=f[b][i];
}
}
return f[a][0];
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&q))
{
init();
for(int i=1; i<=m; i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
g[a].push_back(node(b,c));
g[b].push_back(node(a,c));
unit(a,b);
}
init_lca();
for(int i=1; i<=q; i++)
{
int a,b;
scanf("%d%d",&a,&b);
int fa=finding(a),fb=finding(b);
if(fa!=fb) printf("Not connected\n");
else printf("%d\n",dis[a]+dis[b]-2*dis[lca(a,b)]);
}
}
return 0;
}