牛棚安排
jzoj 1259
题目大意:
有nnn头牛和mmm个牛棚,每头牛有自己第1喜欢,第2喜欢……第mmm喜欢的牛棚(开心度分别为m,m−1,m−2……1m,m-1,m-2……1m,m−1,m−2……1),然后读入mmm个数表示第iii个牛棚最多可以进多少头牛,现在让所有牛都进入到牛棚内,问最开心的牛和最伤心的牛开心度之差最小是多少
输入样例
6 4
1 2 3 4
2 3 1 4
4 2 3 1
3 1 2 4
1 3 4 2
1 4 2 3
2 1 3 2
输出样例
2
样例解释
每头奶牛都能被安排进她的第一或第二喜欢的牛棚。下面给出一种合理的分配方案:奶牛1和奶牛5住入牛棚1,牛棚2由奶牛2独占,奶牛4住进牛棚3,剩下的奶牛3和奶牛6安排到牛棚4。
解题思路
先二分枚举答案,然后枚举每一个区间,接下来用最大流求二分图的匹配即可
代码
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
int n, m, l, r, mid, sum, s, t, tot, b[50], head[2000], dep[2000], v[2100][50];const int inf = 1 << 29;struct rec
{int to, next, edge;
}a[40500];queue<int> d;void add(int x, int y, int z)
{a[++tot].to = y;a[tot].edge = z;a[tot].next = head[x];head[x] = tot;a[++tot].to = x;a[tot].edge = 0;a[tot].next = head[y];head[y] = tot;
}bool bfs()
{memset(dep, 0, sizeof(dep));while(!d.empty()) d.pop();d.push(s);dep[s] = 1;while (!d.empty()){int h = d.front();d.pop();for (int i = head[h]; i; i = a[i].next)if (!dep[a[i].to] && a[i].edge){dep[a[i].to] = dep[h] + 1;if (a[i].to == t) return true;d.push(a[i].to);}}return false;
}int dinic(int x, int flow)
{if (x == t) return flow;int rest = 0, k;for (int i = head[x]; i; i = a[i].next)if (dep[x] + 1 == dep[a[i].to] && a[i].edge){k = dinic(a[i].to, min(a[i].edge, flow - rest));if (!k) dep[a[i].to] = 0;rest += k;a[i].edge -= k;a[i^1].edge += k;if (rest == flow) return rest;}return rest;
}bool js(int x)
{s = 0;t = n + m + 1;for (int i = 1; i <= m - x + 1; ++i)//开头位置{memset(head, 0, sizeof(head));tot = 0;for (int j = 1; j <= m; ++j)add(n + j, t, b[j]);//连到Tfor (int j = 1; j <= n; ++j){add(s, j, 1);//连到Sfor (int k = i; k - i + 1 <= x; ++k)add(j, n + v[j][k], 1);//连边}sum = 0;while(bfs())//找增广路sum += dinic(s, inf);//流if (sum == n) return true;//可以满足}return false;
}
int main()
{scanf("%d%d", &n, &m);for (int i = 1; i <= n; ++i)for (int j = 1; j <= m; ++j)scanf("%d", &v[i][j]);//先存下来,到时再连边for (int i = 1; i <= m; ++i)scanf("%d", &b[i]);l = 1;r = m;while(l < r)//二分枚举{mid = (l + r) >> 1;if (js(mid)) r = mid;else l = mid + 1;}printf("%d", l);return 0;
}