Connections between cities
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1107 Accepted Submission(s): 376
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应用。。。今天状态实在是差阿,这种水题都要wa好几次~~~
代码:
#include<cstdio>
using namespace std;
const int mm=2222222;
const int mn=11111;
int t[mm],d[mm],p[mm],ans[mm];
int h[mn],q[mn],f[mn],id[mn],dis[mn];
bool vis[mn];
int i,j,k,n,m,c,e,cnt;
void add(int u,int v,int c,int h[])
{
t[e]=v,d[e]=c,p[e]=h[u],h[u]=e++;
t[e]=u,d[e]=c,p[e]=h[v],h[v]=e++;
}
int find(int x)
{
if(f[x]==x)return x;
return f[x]=find(f[x]);
}
void tarjan(int u)
{
int i,v;
id[u]=cnt;
vis[f[u]=u]=1;
for(i=q[u];i;i=p[i])
if(vis[v=t[i]])
ans[d[i]]=(id[v]==id[u])?dis[u]+dis[v]-(dis[find(v)]<<1):-1;
for(i=h[u];i;i=p[i])
if(!vis[v=t[i]])
dis[v]=dis[u]+d[i],tarjan(v),f[v]=u;
}
void in(int &a)
{
char c;
while((c=getchar())<'0'||c>'9');
for(a=0;c>='0'&&c<='9';c=getchar())a=a*10+c-'0';
}
void out(int x)
{
if(x>9)out(x/10);
putchar(x%10+48);
}
int main()
{
while(scanf("%d%d%d",&n,&m,&c)!=-1)
{
for(i=e=1;i<=n;++i)h[i]=q[i]=id[i]=vis[i]=0;
while(m--)in(i),in(j),in(k),add(i,j,k,h);
for(k=1;k<=c;++k)in(i),in(j),add(i,j,k,q);
for(i=cnt=1;i<=n;++i,++cnt)
if(!vis[i])dis[i]=0,tarjan(i);
for(i=1;i<=c;++i)
if(ans[i]<0)puts("Not connected");
else out(ans[i]),puts("");
}
return 0;
}
本文探讨了在世界大战X之后的城市重建问题,特别是在不同城市间运输关键材料所需的路径算法。考虑到大多数道路已被摧毁,文章提出了一种算法来确定两座城市间是否存在路径,并在存在路径的情况下找出最短路径。

13万+

被折叠的 条评论
为什么被折叠?



