本文主要是介绍洛谷 P2071 座位安排 (最大流 + 建图),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
2020.7.15
今天先开个小差,这图书馆接近零下的气温给爷冻傻了,这还咋写题?马上回去了,练一练网络和tarjan吧。
这道题很简单,问有2n个人,n排座位,每个人都有喜欢的两个座位,最多能安置多少个人?这不就是二分图嘛,切了它!首先看到一排有两个座位,换句话说这个点具有2对1的属性,要素察觉,我们用拆点处理一下,每一排座位分为出边和入边两个流量,入到出流量为2,这样就可以一一对应了,然后跑一边最大流就ok了。好消息是AC了,悲剧是我发现我好像想多了,我把拆点这个步骤去掉好像也能AC,哭了,才想起来好像左右没什么关系,如果分为左和右那我的方法可能管用?但好像并不需要的亚子。
令人吐血的AC记录:
代码(拆点):
#include <bits/stdc++.h>
using namespace std;
#define limit (100000 + 5)//防止溢出
#define INF 0x3f3f3f3f
#define inf 0x3f3f3f3f3f
#define lowbit(i) i&(-i)//一步两步
#define EPS 1e-6
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);
#define ff(a) printf("%d\n",a );
#define pi(a,b) pair<a,b>
#define rep(i, a, b) for(ll i = a; i <= b ; ++i)
#define per(i, a, b) for(ll i = b ; i >= a ; --i)
#define MOD 998244353
#define traverse(u) for(int i = head[u]; ~i ; i = edge[i].next)
#define FOPEN freopen("C:\\Users\\tiany\\CLionProjects\\acm_01\\data.txt", "rt", stdin)
#define FOUT freopen("C:\\Users\\tiany\\CLionProjects\\acm_01\\dabiao.txt", "wt", stdout)
typedef long long ll;
typedef unsigned long long ull;
inline ll read(){ll sign = 1, x = 0;char s = getchar();while(s > '9' || s < '0' ){if(s == '-')sign = -1;s = getchar();}while(s >= '0' && s <= '9'){x = (x << 3) + (x << 1) + s - '0';s = getchar();}return x * sign;
}//快读
inline void write(ll x){if(x < 0) putchar('-'),x = -x;if(x / 10) write(x / 10);putchar(x % 10 + '0');
}
int n,m,vs,ve,p;
int layer[limit],head[limit], cnt;
struct node{int to ,next;ll flow, w;
}edge[limit];
ll max_flow;
void add_one(int u , int v, ll flow = 0){edge[cnt].to = v;edge[cnt].next = head[u];edge[cnt].flow = flow;edge[cnt].w = 0;head[u] = cnt++;
}
inline void add(int u, int v, ll flow){add_one(u,v,flow);add_one(v, u,0);
}
inline void init(bool flag = true){if(flag){memset(head, -1, sizeof(head));cnt = 0;}else{memset(layer, -1, sizeof(layer));}
}
inline bool bfs(){init(false);queue<int>q;layer[vs] = 0;//从第0层开始q.push(vs);while (q.size()){int u = q.front();q.pop();traverse(u){int v = edge[i].to,flow = edge[i].flow;if(layer[v] == -1 && flow > 0){layer[v] = layer[u] + 1;//迭代加深q.push(v);}}}return ~layer[ve];
}
ll dfs(int u, ll flow){if(u == ve)return flow;ll rev_flow = 0,min_flow;traverse(u){int v =edge[i].to;ll t_flow = edge[i].flow;if(layer[v] == layer[u] + 1 && t_flow > 0){min_flow = dfs(v, min(flow, t_flow));flow -= min_flow;edge[i].flow -= min_flow;rev_flow += min_flow;edge[i^1].flow += min_flow;if(!flow)break;}}if(!rev_flow)layer[u] = -1;return rev_flow;
}
void dinic(){while (bfs()){max_flow += dfs(vs,inf);}
}
int main() {
#ifdef LOCALFOPEN;
#endifinit();n = read();vs = 50001, ve = vs + 1;//将座位拆成两个点rep(i ,1,n){add(i + n * 2 , i + n * 3, 2);//每个点之间有两个流量}rep(i ,1,n * 2){add(vs, i, 1);//本位置心相连int x = read(), y = read();add(i, n * 2 + x, 1);add(i, n * 2 + y, 1);}//拆点rep(i ,1, n){add(n * 3 + i, ve,2);}dinic();write(max_flow);return 0;
}
这篇关于洛谷 P2071 座位安排 (最大流 + 建图)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!