详细解法参考胡伯涛的《最小割模型在信息学竞赛中的应用 》论文,下面做了一些注释,仅供参考。。。
代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
const int maxn = 1500;
const int maxm = 10000;
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
using namespace std;
inline int read()
{
int x=0,t=1,c;
while(!isdigit(c=getchar()))if(c=='-')t=-1;
while(isdigit(c))x=x*10+c-'0',c=getchar();
return x*t;
}
int n, m;
int head[maxn],cur[maxn],nx[maxm<<1],to[maxm<<1],ppp=0,thead[maxn];
double flow[maxm<<1];
struct Dinic {
int dis[maxn];
int s, t;
double ans;
void init() {
memset(head, -1, sizeof(head));
ppp = 0;
}
void AddEdge(int u, int v, double c)
{
to[ppp]=v;flow[ppp]=c;nx[ppp]=head[u];head[u]=ppp++;swap(u,v);
to[ppp]=v;flow[ppp]=0;nx[ppp]=head[u];head[u]=ppp++;
}
bool BFS()
{
memset(dis, -1, sizeof(dis));
dis[s] = 1;
queue<int> Q;
Q.push(s);
while(!Q.empty())
{
int x = Q.front();
Q.pop();
for(int i = head[x]; ~i; i = nx[i])
{
if(flow[i] > 0 && dis[to[i]] == -1)
{
dis[to[i]] = dis[x] + 1;
Q.push(to[i]);
}
}
}
return dis[t] != -1;
}
double DFS(int x, double maxflow) {
if(x == t || !maxflow){
ans += maxflow;
return maxflow;
}
double ret = 0;
double f;
for(int &i = cur[x]; ~i; i = nx[i]) {
if(dis[to[i]] == dis[x] + 1 && (f = DFS(to[i], min(maxflow, flow[i])))) {
ret += f;
flow[i] -= f;
flow[i^1] += f;
maxflow -= f;
if(!maxflow)
break;
}
}
return ret;
}
double solve(int source, int tank) {
s = source;
t = tank;
ans = 0;
while(BFS()) {
memcpy(cur, head, sizeof(cur));
DFS(s, INF);
}
return ans;
}
}dinic;
int d[maxn], u[maxn], v[maxn], cnt;
bool vst[maxn];
void build(double g) {
dinic.init();
int s = 0, t = n + 1;
for(int i = 1; i <= n; i++) {
dinic.AddEdge(s, i, m);
dinic.AddEdge(i, t, m + 2 * g - d[i]);
}
for(int i = 1; i <= m; i++) {
dinic.AddEdge(u[i], v[i], 1.0);
dinic.AddEdge(v[i], u[i], 1.0);
}
}
void find_dfs(int uu) {
cnt++;
vst[uu] = 1;
for(int i = head[uu]; ~i; i = nx[i]) {
int vv = to[i];
if(flow[i] > eps && !vst[vv]) {
find_dfs(vv);
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("poj_in.txt", "r", stdin);
#endif
n = read(), m = read();
if(m == 0) {
printf("1\n1\n");
return 0;
}
for(int i = 1; i <= m; i++) {
u[i] = read(), v[i] = read();
d[u[i]]++, d[v[i]]++;
}
double front = 0, back = m;
double e = 1.0 / n / n; //引理4.1 无向图G中,
while(back - front >= e) { //任意两个具有不同密度的子图G1,G2
double g = (front + back) / 2.0;//它们的密度差不小于1/n/n
build(g);
double tmp = dinic.solve(0, n + 1);
if((n * m - tmp) / 2.0 > eps) //即使两边乘以-1,依然要趋于0
front = g; //大于0说明g还不够大,使得tmp太小
else
back = g;
}
build(front); //得到比例后,重新建图
dinic.solve(0, n + 1);//没有流量的是红色的边
find_dfs(0); //故判断某条边是否有流量
printf("%d\n", cnt - 1);//即可知道某点是否在集合中
for(int i = 1; i <= n; i++) {
if(vst[i])
printf("%d\n", i);
}
return 0;
}