lightoj1063 Ant Hills

思路:无向图中割点个数的判定。直接Tarjan抛一边就好了。

如果u是这个搜索树的根且有多个儿子节点,,,那么这个根是割点,因为去掉这个点后,他的儿子间是不能连通的。

如果u 不是根,如果它的某个儿子节点low[v] >= dfn[u]那么u也是一个割点。

// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
// #define DEBUG
#ifdef DEBUG
#define debug(...) printf( __VA_ARGS__ )
#else
#define debug(...)
#endif
#define MEM(x,y) memset(x, y,sizeof x)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int maxn = 10010;
int dfn[maxn], low[maxn];
int Time;
int sum;
vector<int> G[maxn];
set<int> s;
void Tarjan(int u,int fa){
	dfn[u] =low[u] = Time++;
	int child = 0, cnt = 0;
	for (int i = 0;i < G[u].size();++i){
		int v = G[u][i];
		if (v == fa && cnt == 0){
			cnt = 1;
			continue;
		}
		if (dfn[v] == -1){
			Tarjan(v, u);
			low[u] = min(low[u], low[v]);
			if (fa == -1 && child != 0) {
				// printf("(%d,%d)\n",u,v);
				s.insert(u);
			}
			if (fa != -1 && low[v] >= dfn[u]){
				// printf("(%d,%d)\n",u,v);
				s.insert(u);
			}
			child++;
		}
		else low[u] = min(low[u], dfn[v]);
	}
}
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	int t;
	int icase = 0;
	int n, m;
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		for (int i = 1;i <= n;++i)
			G[i].clear();
		while(m--){
			int u,v;
			scanf("%d%d",&u,&v);
			G[u].push_back(v);
			G[v].push_back(u);
		}
		memset(dfn, -1,sizeof dfn);
		sum = Time = 0;
		s.clear();
		for (int i = 1;i <= n;++i)
			if (dfn[i] == -1) Tarjan(i, -1);
		printf("Case %d: %d\n", ++icase, (int)s.size());
	}
	return 0;
}


你可能感兴趣的:(lightoj1063 Ant Hills)