您的位置:首页 > 编程语言 > Go语言

【POJ 2762】Going from u to v or from u ? (Tarjan + 拓扑排序)

2017-08-20 20:16 465 查看

传送门

Going from u to v or from u ?

题意:给出一张图,判断任意点对(x,y)是否能够从x走到y 或者 从y走到x。

I think

先用tarjan求强连通分量缩点。然后拓扑排序检查是否存在1个以上的点入度为0,若是,则不满足条件。

Code

#include<cstdio>
const int sm = 1e3+5;
const int sn = 6e3+5;

int T,N,M,tot,cnt,Bcnt;
int to[sn],nxt[sn],hd[sm];
int _to[sn],_nxt[sn],_hd[sm];
int Bn[sm],Lw[sm];
int top,instk[sm],stk[sm];
int Blg[sm],Rd[sm];

void read(int &x) {
char ch=getchar();x=0;
while(ch>'9'||ch<'0') ch=getchar();
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
}
int Min(int x,int y) { return x<y?x:y; }

void Add(int u,int v) {
to[++tot]=v,nxt[tot]=hd[u],hd[u]=tot;
}
void Ins(int u,int v) {
_to[++tot]=v,_nxt[tot]=_hd[u],_hd[u]=tot,Rd[v]++;
}
void Tarjan(int x) {
int j;
Bn[x]=Lw[x]=++cnt;
instk[x]=true,stk[++top]=x;
for(int i=hd[x];i;i=nxt[i]) {
j=to[i];
if(!Bn[j]) {
Tarjan(j);
Lw[x]=Min(Lw[x],Lw[j]);
}
else if(instk[j]&&Lw[j]<Lw[x])
Lw[x]=Lw[j];
}
if(Lw[x]==Bn[x]){
++Bcnt;
do{
j=stk[top--];
instk[j]=false;
Blg[j]=Bcnt;
}while(j!=x);
}
}
bool Topsort() {
int t;top=0;
for(int i=1;i<=Bcnt;++i)
if(Rd[i]==0)
stk[++top]=i;
while(top) {
t=stk[top--];
if(top) return false;
for(int i=_hd[t];i;i=_nxt[i]) {
Rd[_to[i]]--;
if(Rd[_to[i]]==0)
stk[++top]=_to[i];
}
}
return true;
}
int main() {
int u[sn],v[sn]; bool flag;
read(T);
while(T--) {
read(N),read(M);

tot=cnt=Bcnt=top=0;
for(int i=1;i<=N;++i)
Rd[i]=Bn[i]=_hd[i]=hd[i]=instk[i]=0;

for(int i=1;i<=M;++i) {
read(u[i]),read(v[i]);
Add(u[i],v[i]);
}
for(int i=1;i<=N;++i)
if(!Bn[i]) Tarjan(i);

tot=0;
for(int i=1;i<=M;++i)
if(Blg[u[i]]!=Blg[v[i]])
Ins(Blg[u[i]],Blg[v[i]]);

flag=Topsort();
puts(flag?"Yes":"No");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: