Description
Input
Output
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.
#include<iostream> #include<cstring> #include<cstdio> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) using namespace std; const int nn=1e4+9; const int mm=2e6+nn+nn; class Edge { public:int v,next,w; }e[mm]; int head[nn],qhead[nn],edge,ans[mm],dis[nn]; bool vis[nn]; int rt[nn],N,M,C,id[nn]; void data() { clr(head,-1);clr(qhead,-1);edge=0; } void add(int u,int v,int w,int*h) { e[edge].v=v;e[edge].w=w;e[edge].next=h[u];h[u]=edge++; } int find(int x) { if(rt[x]^x) rt[x]=find(rt[x]); return rt[x]; } void tarjan(int u,int bcc) { int v; id[u]=bcc; vis[u]=1;rt[u]=u; for(int i=head[u];~i;i=e[i].next) { v=e[i].v; if(vis[v])continue; dis[v]=dis[u]+e[i].w; tarjan(v,bcc);rt[v]=u; } for(int i=qhead[u];~i;i=e[i].next) { v=e[i].v; if(!vis[v])continue; ans[e[i].w]=(id[u]==id[v])?dis[u]+dis[v]-dis[find(v)]*2:-1; } } void getans() { clr(vis,0);clr(id,0); int bcc=0; FOR(i,1,N) if(!vis[i]) dis[i]=0,tarjan(i,++bcc); } int main() { int a,b,c; while(~scanf("%d%d%d",&N,&M,&C)) { data(); FOR(i,1,M) { scanf("%d%d%d",&a,&b,&c); add(a,b,c,head);add(b,a,c,head); } FOR(i,1,C) { scanf("%d%d",&a,&b);add(a,b,i,qhead);add(b,a,i,qhead); } getans(); FOR(i,1,C) if(ans[i]<0)printf("Not connected\n"); else printf("%d\n",ans[i]); } }
#include<iostream> #include<cstring> #include<cstdio> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) #define ll(x) (1<<x) using namespace std; const int nn=4e4+9; const int mm=4e4+9; class Edge { public:int v,next,w; }e[mm]; int head[nn],edge,dis[nn],to[nn],dfs_clock; int vis[nn],rmq[nn][30]; int rt[nn],N,M,C,bit[nn]; void data() { clr(head,-1);edge=0; } void add(int u,int v,int w,int*h) { e[edge].v=v;e[edge].w=w;e[edge].next=h[u];h[u]=edge++; } int find(int x) { if(rt[x]^x) rt[x]=find(rt[x]); return rt[x]; } void uni(int a,int b) { a=find(a);b=find(b); rt[a]=b; } void dfs(int u,int dep)//一遍欧拉路径 { int v; to[dfs_clock]=u;//存欧拉路径 dis[u]=dep; vis[u]=dfs_clock++; for(int i=head[u];~i;i=e[i].next) { v=e[i].v; if(vis[v]==-1) { dfs(v,dep+e[i].w); to[dfs_clock++]=u; } } } void ST(int N) { bit[0]=-1; FOR(i,1,N)bit[i]=(i&(i-1))==0?bit[i-1]+1:bit[i-1]; FOR(i,0,N) rmq[i][0]=dis[ to[i] ]; FOR(i,1,bit[N]) for(int j=0;j+ll(i)-1<=N;++j) rmq[j][i]=min(rmq[j][i-1],rmq[j+ll(i-1)][i-1]); } int RMQ(int l,int r) { int t=bit[r-l+1]; r-=ll(t)-1; return min(rmq[l][t],rmq[r][t]); } int main() { int a,b,c; while(~scanf("%d%d%d",&N,&M,&C)) { data();clr(vis,-1); FOR(i,0,N)rt[i]=i; FOR(i,1,M) { scanf("%d%d%d",&a,&b,&c); add(a,b,c,head);add(b,a,c,head); uni(a,b); } FOR(i,1,N)///虚点 0 ,虚边得有值,不然查到0不一定是根点 if(rt[i]==i) add(0,i,1,head),add(i,0,1,head); dfs_clock=0; dfs(0,0); ST(dfs_clock-1); FOR(i,1,C) { scanf("%d%d",&a,&b); int ta=vis[a]; int tb=vis[b]; if(ta>tb)swap(ta,tb); int ddd=RMQ(ta,tb); if(ddd==0)printf("Not connected\n"); else printf("%d\n",dis[a]+dis[b]-2*ddd); } } }