hdu3861(tarjan缩点 + Hungary)

题意:给出一张有向图,要求你将这些点进行划分,划分依据如下

1.如果两个点互相可达,那么这两个点必须在同一个集合中;

2.同一个集合中的两个点u,v要满足要么u->v || v->u;

3.一个点只能被划分到同一个集合;

问最少能划分成几个集合

思路:对于条件一就是强联通分量;对于条件2,3得话就要球出来最小路径覆盖,所以可以将所有的强联通分量进行缩点,桥作为连接,然后匈牙利一下,求出最大匹配数目,最后的结果就是强联通分量数- 最大匹配数


/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
*****************************************/
// #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>
using namespace std;
#define MEM(a,b) memset(a,b,sizeof a)
#define pk push_back
template<class T> inline T Get_Max(const T&a,const T&b){return a < b?b:a;}
template<class T> inline T Get_Min(const T&a,const T&b){return a < b?a:b;}
typedef long long ll;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
struct Edge{
	int to,nxt;
}E[100010];
struct node{
	int x,y;
}node[100010];
int head[5010],sccno[5010],pre[5010],lowlink[5010],st[5010],link[5010];
int n,m,tot,scc_tot,dfs_clock,top;
bool vis[5010];
void Addedge(int u,int v){
	E[tot].to = v;
	E[tot].nxt = head[u];
	head[u] = tot++;
}
void Init(){
	scanf("%d%d",&n,&m);
	MEM(head, -1);
	tot = 0;
	for (int i = 1;i <= m;i++){
		scanf("%d%d",&node[i].x,&node[i].y);
		Addedge(node[i].x,node[i].y);
	}
}
void DFS(int u){
	pre[u] = lowlink[u] = ++dfs_clock;
	st[++top] = u;
	for (int i = head[u];i != -1;i = E[i].nxt){
		int v = E[i].to;
		if (!pre[v]){
			DFS(v);
			lowlink[u] = Get_Min(lowlink[v],lowlink[u]);
		}
		else if (!sccno[v]){
			lowlink[u] = Get_Min(lowlink[u],pre[v]);
		}
	}
	int x;
	if (lowlink[u] == pre[u]){
		++scc_tot;
		while(true){
			x = st[top--];
			sccno[x] = scc_tot;
			if (x == u) break;
		}
	}
}
bool dfs2(int u){
	for (int i = head[u];i != -1;i = E[i].nxt){
		int v = E[i].to;
		if (!vis[v]){
			vis[v] = true;
			if (link[v] == -1 || dfs2(link[v])){
				link[v] = u;
				return true;
			}
		}
	}
	return false;
}
void solve(){
	MEM(pre, 0);
	MEM(sccno, 0);
	scc_tot = top = dfs_clock = 0;
	for (int i = 1;i <= n;i++){
		if (!pre[i]) DFS(i);
	}
	MEM(head, -1);
	tot = 0;
	int u,v;
	for (int i = 1;i <= m;i++){
		u = sccno[node[i].x];
		v = sccno[node[i].y];
		if (u != v) Addedge(u,v);//去掉自环;
	}
	int ans = 0;
	MEM(link, -1);
	for (int i = 1;i <= scc_tot;i++){
		MEM(vis, false);
		if (dfs2(i)) ans++;
	}
	printf("%d\n",scc_tot - ans);
}
int main()
{	
	// ios::sync_with_stdio(false);
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	int test;
	scanf("%d",&test);
	while(test--){
		Init();
		solve();
	}
	return 0;
}


你可能感兴趣的:(图论,二分图匹配)