P2857 Steady Cow Assignment

最大流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define N 1200
#define M 100005
#define inf 0x3f3f3f3f
using namespace std;
int n, m;
struct Edge {
int v, cap, flow, next;
};
Edge e[M];
int head[N], cnt;
int cur[N];
int dist[N], vis[N];
int num[N];
int val[N][25];
void init(){
cnt = 1; memset(head, 0, sizeof(head));
}
void add(int u, int v, int w){
e[++cnt] = (Edge) {v, w, 0, head[u]}; head[u] = cnt;
e[++cnt] = (Edge) {u, 0, 0 ,head[v]}; head[v] = cnt;
}
void input(){
for(int i = 1; i <= n; i += 1)
for(int j = 1; j <= m; j += 1)
scanf("%d", &val[i][j]);
for(int i = 1; i <= m; i += 1){
scanf("%d", &num[i]);
}
}
void getmap(int l, int r){
for(int i = 1; i <= n; i += 1)
add(0, i, 1);
for(int j = 1; j <= m; j += 1)
add(n + j, n + m + 1, num[j]);
for(int i = 1; i <= n; i += 1)
for(int j = l; j <= r; j += 1)
add(i, val[i][j] + n, 1);
}
bool BFS(int st ,int ed){
queue<int>q;
memset(vis, 0 ,sizeof(vis));
memset(dist, -1, sizeof(dist));
vis[st] = 1;
dist[st] = 0;
q.push(st);
while(!q.empty()){
int u = q.front();
q.pop();
for(int i = head[u]; i; i = e[i].next){
Edge E = e[i];
if(!vis[E.v] && E.cap > E.flow){
vis[E.v] = 1;
dist[E.v] = dist[u] + 1;
if(E.v == ed)
return true;
q.push(E.v);
}
}
}
return false;
}
int DFS(int x, int ed, int a){
if(x == ed || a == 0)
return a;
int flow = 0, f;
for(int &i = cur[x]; i; i = e[i].next){
Edge &E = e[i];
if(dist[E.v] == dist[x] + 1 && (f = DFS(E.v, ed, min(a, E.cap - E.flow))) > 0){
E.flow += f;
e[i ^ 1].flow -= f;
a -= f;
flow += f;
if(not a) break;
}
}
return flow;
}
int maxflow(int st, int ed){
int flowsum = 0;
while(BFS(st,ed)){
memcpy(cur, head, sizeof(head));
flowsum += DFS(st, ed, inf);
}
return flowsum;
}
int main(){
while(scanf("%d%d", &n, &m) != EOF){
input();
int ans = inf;
for(int i = 1; i <= m; i += 1){
for(int j = i; j <= m; j += 1){
init();
getmap(i, j);
if(maxflow(0, n + m + 1) == n)
ans = min(ans, j - i + 1);
}
}
printf("%d\n", ans);
}
return 0;
}

-------------本文结束感谢您的阅读-------------