題目鏈接:點擊查看
題目大意:給出一張 n 個點 m 條邊的有向圖,問對于任意不相等的 a 和 b ,是否滿足存在 a 到 b 的一條路徑或者 b 到 a 的一條路徑
題目分析:判斷是否存在路徑的話,對于一個環來說,顯然環中的任意兩個節點互相都是可達的,所以對題目不具有貢獻,我們可以先用 tarjan 縮一下點,這樣就可以在新圖上拓撲了,對于新圖來說拓撲序必須唯一才能滿足題意,否則的話肯定會存在著兩個點 a 和 b 不滿足題意
代碼:
?
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=2e3+100;const int M=1e4+100;struct Egde
{int to,next;
}edge1[M],edge2[M];int head1[N],head2[N],low[N],dfn[N],c[N],Stack[N],num,cnt,cnt2,cnt1,dcc,n,m,top,in[N];bool ins[N];vector<int>scc[N];void addedge1(int u,int v)
{edge1[cnt1].to=v;edge1[cnt1].next=head1[u];head1[u]=cnt1++;
}void addedge2(int u,int v)
{edge2[cnt2].to=v;edge2[cnt2].next=head2[u];head2[u]=cnt2++;
}void tarjan(int u)
{dfn[u]=low[u]=++num;Stack[++top]=u;ins[u]=true;for(int i=head1[u];i!=-1;i=edge1[i].next){int v=edge1[i].to;if(!dfn[v]){tarjan(v);low[u]=min(low[u],low[v]);}else if(ins[v])low[u]=min(low[u],dfn[v]);}if(dfn[u]==low[u]){cnt++;int v;do{v=Stack[top--];ins[v]=false;c[v]=cnt;scc[cnt].push_back(v);}while(u!=v);}
}void solve()
{for(int i=1;i<=n;i++)//縮點 if(!dfn[i])tarjan(i);
}void build()//縮點+連邊
{solve();for(int i=1;i<=n;i++){for(int j=head1[i];j!=-1;j=edge1[j].next){int u=i;int v=edge1[j].to;if(c[u]!=c[v]){addedge2(c[u],c[v]);in[c[v]]++;}}}
}bool topo()
{queue<int>q;for(int i=1;i<=cnt;i++)if(!in[i])q.push(i);if(q.size()>1)return false;while(q.size()){int u=q.front();q.pop();int tot=0;for(int j=head2[u];j!=-1;j=edge2[j].next){int v=edge2[j].to;if(--in[v]==0){tot++;q.push(v);}}if(tot>1)return false;}return true;
}void init()
{for(int i=0;i<N;i++)scc[i].clear();top=cnt=cnt1=cnt2=num=dcc=0;memset(head2,-1,sizeof(head2));memset(head1,-1,sizeof(head1));memset(low,0,sizeof(low));memset(dfn,0,sizeof(dfn));memset(c,0,sizeof(c));memset(ins,false,sizeof(ins));memset(in,0,sizeof(in));
}int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);int w;cin>>w;int kase=0;while(w--){init();scanf("%d%d",&n,&m);while(m--){int u,v;scanf("%d%d",&u,&v);addedge1(u,v);}build(); if(topo())printf("Case %d: Kalimdor is just ahead\n",++kase);elseprintf("Case %d: The Burning Shadow consume us all\n",++kase);}return 0;
}
?
總結
以上是生活随笔為你收集整理的SDUT - 2604 Thrall’s Dream(tarjan+拓扑)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。