POJ 2553 The Bottom of a Graph
图论,targan
传送门:POJ
传送门:HustOJ
题意
Here are some new definitions. A node v in a graph G=(V,E) is called a sink, if for every node w in G that is reachable from v, v is also reachable from w. The bottom of a graph is the subset of all nodes that are sinks, i.e., bottom(G)={v∈V|∀w∈V:(v→w)⇒(w→v)}. You have to calculate the bottom of certain graphs.
一张有向图,找出所有满足条件的点。
找出符合条件的点a的集合,使得对于任意的b:如果a可以到达b,那么b一定可以到达a。
思路
有向图缩点后得到DAG,我们要找的就是DAG上出度为0的点。
学到的就是缩点后如何计算出度入度。
代码
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define _ ios_base::sync_with_stdio(0),cin.tie(0)
#define M(a,b) memset(a,b,sizeof(a))
using namespace std;
const int MAXN=5005;
const int oo=0x3f3f3f3f;
typedef __int64 LL;
const LL loo=4223372036854775807ll;
typedef long double LB;
const LL mod=1e9+7;
typedef long long LL;
struct Targan
{
//sccno[i]为i所在的dfs块编号
vector<int> G[MAXN];
int pre[MAXN], lowlink[MAXN], sccno[MAXN], dfs_clock, scc_cnt;
stack<int> S;
void init()
{
for(int i=0;i<MAXN;i++) G[i].clear();
while(!S.empty()) S.pop();
}
void addedge(int a, int b)//加边,单向边a到b
{
G[a].push_back(b);
}
void dfs(int u)
{
pre[u]=lowlink[u]=++dfs_clock;
S.push(u);
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(!pre[v])
{
dfs(v);
lowlink[u]=min(lowlink[u], lowlink[v]);
}
else if(!sccno[v])
{
lowlink[u]=min(lowlink[u], pre[v]);
}
}
if(lowlink[u]==pre[u])
{
scc_cnt++;
while(true)
{
int x=S.top();S.pop();
sccno[x]=scc_cnt;
if(x==u) break;
}
}
}
void find_scc(int n)
{
dfs_clock=scc_cnt=0;
M(sccno, 0);M(pre, 0);
for(int i=1;i<=n;i++)//注意修改取值范围
{
if(!pre[i]) dfs(i);
}
}
};
int oudegree[MAXN];
int main()
{
_;
int n;
Targan targan;
while(cin>>n&&n!=0)
{
targan.init();
M(oudegree, 0);
int m;cin>>m;
for(int i=0;i<m;i++)
{
int a, b;cin>>a>>b;
targan.addedge(a, b);
}
targan.find_scc(n);
for(int i=1;i<=n;i++)
{
for(int j=0;j<targan.G[i].size();j++)
{
int to=targan.G[i][j];
if(targan.sccno[i]!=targan.sccno[to])
{
oudegree[targan.sccno[i]]=1;
}
}
}
vector<int> res;
for(int i=1;i<=n;i++)
{
if(oudegree[targan.sccno[i]]==0)
{
res.push_back(i);
}
}
for(int i=0;i<res.size();i++)
{
cout<<res[i];
if(i!=res.size()-1) cout<<' ';
}
cout<<endl;
}
return 0;
}