点击打开链接
题意是说给你一个森林,让你求两点之间的最近距离。
lca求最近公共祖先,如果不是在同一棵树上,则输出Not connected。
Connections between cities
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3528 Accepted Submission(s): 1020
Total Submission(s): 3528 Accepted Submission(s): 1020
Problem Description
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.
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 6HintHint Huge input, scanf recommended.
Source
Recommend
gaojie
题意是说给你一个森林,让你求两点之间的最近距离。
lca求最近公共祖先,如果不是在同一棵树上,则输出Not connected。
#include<stdio.h>
#include<string.h>
#define M 10007
#define N 2222212
int pre[M],dis[M],vis[M],ans[N],id[M];
int s1[N],s2[N],t[N],d[N],p[N];
int n,m,ne,cnt;
int find(int x)
{
while(x!=pre[x])
x=pre[x];
return x;
}
void add(int u,int v,int w,int h[])
{
t[ne]=v,d[ne]=w,p[ne]=h[u],h[u]=ne++;
t[ne]=u,d[ne]=w,p[ne]=h[v],h[v]=ne++;
}
void Tarjan(int u)
{
id[u]=cnt;
pre[u]=u;
vis[u]=1;
for(int i=s2[u];i;i=p[i])
{
int v=t[i];
if(vis[v])
{
if(id[u]==id[v])//在同一棵树下
{
int rt=find(v);//最近公共祖先
ans[d[i]]=dis[u]+dis[v]-2*dis[rt];
}
else
ans[d[i]]=-1;
}
}
for(int i=s1[u];i;i=p[i])
{
int v=t[i];
if(!vis[v])
{
dis[v]=dis[u]+d[i];
Tarjan(v);
pre[v]=u;
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
int n,m,q,i,j;
while(scanf("%d%d%d",&n,&m,&q)!=EOF)
{
for(i=1,ne=1;i<=n;i++)
{
s1[i]=s2[i]=vis[i]=ans[i]=id[i]=pre[i]=0;
}
int u,v,w;
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
add(u,v,w,s1);
}
for(i=1;i<=q;i++)
{
scanf("%d%d",&u,&v);
add(u,v,i,s2);
}
for(i=1,cnt=1;i<=n;i++,cnt++)
if(!vis[i])
{
dis[i]=0;
Tarjan(i);
}
for(i=1;i<=q;i++)
if(ans[i]>=0)
printf("%d\n",ans[i]);
else
printf("Not connected\n");
}
return 0;
}