tarjan算法:
将强连通分量缩成一个点,形成一个新的有向图
学习这个算法是通过解一个题目,看题目意思很明朗,看起来很简单,只是看起来-_-
但是现在我学了这个算法,就不怕了。
问题题出:题目链接
有个大佬,啥都会,萌新们纷纷跑来向大佬学习,但是大佬觉得萌新们太多(sha)了,只想教一部分,然后让那些人再去教别的萌新,如果萌新A会教萌新B,萌新B又会教萌新C,这样,大佬只要教会萌新A,萌新B、C就都会了,这大大的减少了大佬的时间,因为大佬总是很忙的。那么问题来了,大佬至少教多少个人才会让萌新们全都会呢。
解题思路:
首先萌新们的关系会构成有向图,如果萌新A会教萌新B,那么就有一条有向边从A指向B。然后跑一遍tarjan,再缩点,统计入度是0的点的个数就是答案。
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 10000 + 10;
struct E{
int to, next;
}e[maxn],ec[maxn];
vector<int>scc[maxn]; //强连通分量,scc[i]记录连通编号为i的所有顶点编号
int head[maxn], tot;
int stack[maxn], ins[maxn], dfn[maxn], low[maxn], c[maxn];//c数组记录连通的编号
int n, m, num, top, cnt; //n点,m边,num编号dfs序,
int hc[maxn], tc;
int ind[maxn],outd[maxn];
void addedge(int u,int v){
e[++tot].to=v; e[tot].next=head[u]; head[u]=tot;
}
void add_c(int u,int v){
ec[++tc].to = v; ec[tc].next=hc[u]; hc[u]=tc;
}
void tarjan(int x){
dfn[x] = low[x] = ++num;
stack[++top] = x, ins[x] = 1;
for(int i = head[x]; i; i = e[i].next){
int v = e[i].to;
if(!dfn[v]){
tarjan(v);
low[x] = min(low[x], low[v]);
}
else if(ins[v])
low[x] = min(low[x], dfn[v]);
}
if(dfn[x] == low[x]){
cnt++; int y;
do{
y = stack[top--], ins[y] = 0;
c[y] = cnt, scc[cnt].push_back(y);
}while(x != y);
}
}
int main()
{
cin>>n>>m;
int x,y;
for(int i = 1; i <= n; i++){
cin>>x>>y; //x能教y
addedge(x,y);
}
for(int i = 1; i <= n ;i++){
if(!dfn[i]) tarjan(i);
}
int _t = 0; //连通分量的个数
for(int i = 1;i <= n; i++){
_t=max(_t,c[i]);
}
//缩点
for(int x = 1; x <= n ; x++){
for(int i = head[x]; i; i = e[i].next){
int v = e[i].to;
if(c[x]!=c[v])
add_c(c[x],c[v]);
}
}
for(int x = 1 ; x <= _t ;x++){
for(int i = hc[x]; i; i = ec[i].next){
ind[ec[i].to]++;
outd[x]++;
}
}
//for(int i = 1; i<=_t;i++){
//cout<<ind[i]<<' '<<outd[i]<<endl;
//}
//统计入度为零的点
int res = 0;
for(int i = 1; i <= _t; i++){
if(ind[i] == 0) res++;
}
cout<<res<<endl;
return 0;
}