tarjan無向圖求割點,cpp板子

</pre><pre>
<pre name="code" class="cpp">/*
    index時間戳
    dfn[u]即u的dfs序
    low[v]爲dfs時點v可回到的最小時間戳
    點u爲割點當且僅當u的子樹中有任意一個節點v的low[v]>=dfn[u]
    簡而言之:兒子節點v不能不經過父親節點u,到達祖先,如爺爺節點,root節點...,則:父親節點u爲一個割點
    一個圖可能有不止一個割點,這裏我們考慮用flag數組記錄
    進行一次打印。
*/

/*7 91 2 11 3 53 6 96 7 44 7 73 7 65 4 24 3 47 5 3::1 37 81 2 11 3 56 7 44 7 73 7 65 4 24 3 47 5 3::7 3 1*/

#include<cstdio>
#include<algorithm>
using namespace std;
#define MAXN 10001
#define MAXM 50001
int n,m;
struct node {
	int next;
	int to;
	int w;
} E[MAXM];


int head[MAXN],tot;
void add(int u,int v,int w) {
	E[++tot].to=v,E[tot].w=w,E[tot].next=head[u],head[u]=tot;
}

int dfn[MAXN],low[MAXN],flag[MAXN],index,root;
void tarjan(int u,int fa) {
	dfn[u]=low[u]=++index;
	int children=0;
	for(int i=head[u]; i; i=E[i].next) {
		int v=E[i].to;
		if(dfn[v]==0) {
			children++;
			tarjan(v,u),low[u]=min(low[u],low[v]);			
			if(u!=root&&low[v]>=dfn[u])flag[u]=1;
			if(u==root&&children>1)    flag[u]=1;			
		}
		else if(v!=fa)low[u]=min(low[u],dfn[v]);
	}
}

int main() {
	scanf("%d%d",&n,&m);
	for(int i=1; i<=m; i++) {
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		add(u,v,w),add(v,u,w);
	}
	root=1;
	tarjan(1,root);
	for(int i=1;i<=n;i++)if(flag[i])printf("%d ",i);printf("\n");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章