hdu 2874(LCA应用)

来源:互联网 发布:slf4j 日志 sql 编辑:程序博客网 时间:2024/05/17 02:23

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.
 

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 21 3 22 4 35 2 31 44 5
 

Sample Output
Not connected6
Hint
HintHuge input, scanf recommended.
 

Source
2009 Multi-University Training Contest 8 - Host by BJNU
 

Recommend
gaojie
 
题目:http://acm.hdu.edu.cn/showproblem.php?pid=2874
分析:普通的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;}


原创粉丝点击