您的位置:首页 > 产品设计 > UI/UE

4839 -- Traffic Real Time Query System

2017-02-10 19:28 567 查看
真的没必要再在上面花时间了,交标程的事我也不想干,就把代码贴这里算了。
#pragma GCC optimize("O2")
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<ctime>
#include<cstdlib>
#include<cmath>
using namespace std;
#define rep(i,j,k) for(i=j;i<=k;++i)
#define per(i,j,k) for(i=j;i>=k;--i)
#define ll long long
#define db double
#define ldb long double
#define pii pair<int,int>
#define mkp make_pair
#define X first
#define Y second
const int N=10005,M=100005;
int n,m;
struct POINT{int K,ne;}P[M<<1],Pt[M<<1];
int he
,tot,het[N<<1],tott;
inline void add(int x,int y){
P[++tot]=(POINT){y,he[x]};he[x]=tot;
P[++tot]=(POINT){x,he[y]};he[y]=tot;
}
inline void addt(int x,int y){
Pt[++tott]=(POINT){y,het[x]};het[x]=tott;
Pt[++tott]=(POINT){x,het[y]};het[y]=tott;
}
int dfn
,low
,idx,blg[M],blk,tree
,rt
,sec,ic
,stk[M],Tp,vis[M<<1];
void tarjan(int x){
int y,z,p,so=0;
dfn[x]=low[x]=++idx;
for(p=he[x];p;p=P[p].ne)if(!vis[p]){
stk[++Tp]=p,vis[p]=vis[p^1]=1;
if(!dfn[y=P[p].K]){
tarjan(y);
if(low[y]>=dfn[x]){
++so;tree[++blk]=sec;
do{blg[(z=stk[Tp--])>>1]=blk;}while(z!=p);
}
low[x]=min(low[x],low[y]);
}
else
low[x]=min(dfn[y],low[x]);
}
if(rt[sec]==x?so>1:so)
ic[x]=++blk;
}
int pre[N<<1],son[N<<1],sz[N<<1],dad[N<<1],dep[N<<1];
void DFS1(int x,int fa){
int y,p;sz[x]=1;dep[x]=dep[fa]+1;pre[x]=fa;
for(p=het[x];p;p=Pt[p].ne)if(Pt[p].K!=fa){
DFS1(y=Pt[p].K,x);sz[x]+=sz[y];
if(sz[y]>sz[son[x]])son[x]=y;
}
}
void DFS2(int x,int fa){
int y,p;
dad[x]=son[fa]==x?dad[fa]:x;
for(p=het[x];p;p=Pt[p].ne)if(Pt[p].K!=fa)
DFS2(y=Pt[p].K,x);
}
inline int lca(int x,int y){
int fx=dad[x],fy=dad[y];
while(fx!=fy)
if(dep[fx]>dep[fy])
fx=dad[x=pre[fx]];
else
fy=dad[y=pre[fy]];
return dep[x]>dep[y]?y:x;
}
int main(){
//	freopen("r.in","r",stdin);
//	freopen("w.out","w",stdout);
int i,x,y,z,p,Q;int cnt=0;
do{
rep(i,1,n)he[i]=ic[i]=dfn[i]=0;
rep(i,1,blk)het[i]=son[i]=0;
rep(i,2,tot)vis[i]=0;
idx=blk=sec=0;
tott=tot=1;
scanf("%d%d",&n,&m);
if(!n&&!m)break;
if((++cnt)>10)break;
rep(i,1,m){
scanf("%d%d",&x,&y);
add(x,y);
}
rep(i,1,n)if(!dfn[i])tarjan(rt[++sec]=i);
rep(i,1,n)
if(x=ic[i])
for(p=he[i];p;p=P[p].ne)
addt(x,blg[p>>1]);
rep(i,1,sec)if(he[rt[i]]){
x=blg[he[rt[i]]>>1];
DFS1(x,0);DFS2(x,0);
}
for(scanf("%d",&Q);Q--;){
scanf("%d%d",&x,&y);
z=lca(x=blg[x],y=blg[y]);
printf("%d\n",dep[x]+dep[y]-(dep[z]<<1)>>1);
}
}while(1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: