将源点和每个时间点连一条容量为k的边,表示同一时间最多剃k次胡子,
将一个人和对应时间连一条容量为1的边,表示一个人在某个时间只能剃1次,
再将每个人和汇点连一条容量为2的边表示一个人要剃两次。
先是想贪心,结果不对,后来想到网络流,不会写好伤,下来写了好几发才过,写得依然丑。至今没想出贪心反例
对最大流的理解加深了,图论有待加强
#include<bits/stdc++.h> using namespace std; const int INF = 0x3fffffff; const int maxn = 2142; #define PB push_back struct Edge { int from,to,cap,flow; }; vector<Edge> edges; vector<int> G[maxn]; int n,m,S = 2132,T = 2133; int Hum = 2002; void AddEdge(int from,int to,int cap) { edges.PB(Edge{from,to,cap,0}); edges.PB(Edge{to,from,0,0}); m = edges.size(); G[from].PB(m-2); G[to].PB(m-1); } bool vis[maxn]; int d[maxn],cur[maxn]; bool bfs() { memset(vis,0,sizeof(vis)); queue<int> q; q.push(S); d[S] = 0; vis[S] = true; while(q.size()){ int u = q.front(); q.pop(); for(int i = 0; i < G[u].size(); i++){ Edge &e = edges[G[u][i]]; if(!vis[e.to] && e.cap > e.flow){ vis[e.to] = true; d[e.to] = d[u] + 1; q.push(e.to); } } } return vis[T]; } int dfs(int u,int a) { if(u == T || a == 0) return a; int flow = 0, f; for(int &i = cur[u]; i < G[u].size(); i++){ Edge &e = edges[G[u][i]]; if(d[u] + 1 == d[e.to] && (f = dfs(e.to,min(a,e.cap-e.flow))) >0){ e.flow += f; edges[G[u][i]^1].flow -= f; flow += f; a -= f; if(a == 0) break; } } return flow; } int MaxFlow() { int flow = 0; while(bfs()){ memset(cur,0,sizeof(cur)); flow += dfs(S,INF); } return flow; } int ans[101][2]; int main() { //freopen("in.txt","r",stdin); int N,k; scanf("%d%d",&N,&k); int Se = INF,Ed = -INF; for(int i = 0; i < N; i++){ int s,w; scanf("%d%d",&s,&w); w += s; Se = min(Se,s); Ed = max(Ed,w); for(int j = s; j < w; j++){ AddEdge(j,Hum+i,1); } } for(int i = Se; i < Ed; i++){ AddEdge(S,i,k); } for(int i = Hum,maxi = Hum+N; i < maxi; i++){ AddEdge(i,T,2); } int flow = MaxFlow(); if(flow != 2*N){ puts("No"); }else { puts("Yes"); for(int i = Hum,maxi = Hum+N; i < maxi; i++){ int cnt = 0; for(int j = 0; j < G[i].size()&& cnt < 2; j++){ Edge & e = edges[G[i][j]]; if(e.cap == 0 && e.flow == -1){ ans[i-Hum][cnt++] = e.to; } } } for(int i = 0; i < N; i++){ printf("%d %d\n",ans[i][0],ans[i][1]); } } return 0; }
URAL 1774 Barber of the Army of Mages (最大流)
原文:http://www.cnblogs.com/jerryRey/p/4731126.html