一、内容

Farmer John's N (1 <= N <= 1000) cows each reside in one of B (1 <= B <= 20) barns which, of course, have limited capacity. Some cows really like their current barn, and some are not so happy.

FJ would like to rearrange the cows such that the cows are as equally happy as possible, even if that means all the cows hate their assigned barn.

Each cow gives FJ the order in which she prefers the barns. A cow's happiness with a particular assignment is her ranking of her barn. Your job is to find an assignment of cows to barns such that no barn's capacity is exceeded and the size of the range (i.e., one more than the positive difference between the the highest-ranked barn chosen and that lowest-ranked barn chosen) of barn rankings the cows give their assigned barns is as small as possible.

Input

Line 1: Two space-separated integers, N and B

Lines 2..N+1: Each line contains B space-separated integers which are exactly 1..B sorted into some order. The first integer on line i+1 is the number of the cow i's top-choice barn, the second integer on that line is the number of the i'th cow's second-choice barn, and so on.

Line N+2: B space-separated integers, respectively the capacity of the first barn, then the capacity of the second, and so on. The sum of these numbers is guaranteed to be at least N.

Output

Line 1: One integer, the size of the minumum range of barn rankings the cows give their assigned barns, including the endpoints. 

Sample Input

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

Sample Output

2

二、思路

  • 求最大的喜好度 和 最小的喜好度之间的差值最小。 那么可以二分这个差值,然后枚举所有差值空间,只要有一个满足那么就代表这个mid满足。

三、代码

#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1005, M = 25;
struct Node {
int len, my[N];
} mat[M];
int n, m, g[N][M], cnt[M];
bool vis[M];
bool dfs(int u, int s, int e) {
for (int i = s; i <= e; i++) {
int v = g[u][i]; //谷昌
if (vis[v]) continue; vis[v] = true;
if (mat[v].len < cnt[v]) {
mat[v].my[++mat[v].len] = u;
return true;
}
for (int i = 1; i <= mat[v].len; i++) {
if (dfs(mat[v].my[i], s, e)) {
mat[v].my[i] = u; return true;
}
}
}
return false;
}
bool ok(int mid) {
for (int j = 1; j <= m; j++) { //枚举所有区间
bool ok = true;
for (int i = 1; i <= m; i++) mat[i].len = 0;
for (int i = 1; i <= n; i++) {
memset(vis, false, sizeof(vis));
if (!dfs(i, j, j + mid - 1)) {ok = false; break;}
}
if (ok) return true;
}
return false;
}
int main() {
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) scanf("%d", &g[i][j]);
}
for (int i = 1; i <= m; i++) scanf("%d", &cnt[i]);
int l = 1, r = m;
while (l < r) {
int mid = (l + r) >> 1; //最大值减最少值的差值
if (ok(mid)) r = mid;
else l = mid + 1;
}
printf("%d", l);
}
return 0;
}