-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path1149.cpp
122 lines (118 loc) · 2.1 KB
/
1149.cpp
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
115
116
117
118
119
120
121
122
#include <iostream>
#define inf 999999999
using namespace std;
int m,n,ans=0;
int cap[1103][1103]={0};
int flow[1103][1103]={0};
int firstedge[1003]={0};
bool mem[1103]={0};
inline int min(int x,int y)
{
if (x<y) return x;
return y;
}
int maxflow(const int s,int flowleft)
{
if (s==1101) return flowleft;
mem[s]=1;
int i,ret=0;
if (s == 0)
{
for (i=1;i<=m;i++)
{
if (flow[s][i]<cap[s][i])
{
int tmp=maxflow(i,min(flowleft,cap[s][i]-flow[s][i]));
ret+=tmp;
flow[s][i]+=tmp;
flow[i][s]-=tmp;
flowleft-=tmp;
if(flowleft==0)return ret;
}
}
}
else if (s >= 1 && s <= m)
{
i = firstedge[s];
if (flow[s][i]<cap[s][i])
{
int tmp=maxflow(i,min(flowleft,cap[s][i]-flow[s][i]));
ret+=tmp;
flow[s][i]+=tmp;
flow[i][s]-=tmp;
flowleft-=tmp;
if(flowleft==0)return ret;
}
}
else if (s > 1000)
{
for (i=1001;i<=1000+n;i++)
{
if (i!=s&&!mem[i]&&flow[s][i]<cap[s][i])
{
int tmp=maxflow(i,min(flowleft,cap[s][i]-flow[s][i]));
ret+=tmp;
flow[s][i]+=tmp;
flow[i][s]-=tmp;
flowleft-=tmp;
if(flowleft==0)return ret;
}
}
i = 1101;
if (flow[s][i]<cap[s][i])
{
int tmp=maxflow(i,min(flowleft,cap[s][i]-flow[s][i]));
ret+=tmp;
flow[s][i]+=tmp;
flow[i][s]-=tmp;
flowleft-=tmp;
if(flowleft==0)return ret;
}
}
return ret;
}
int main()
{
cin>>m>>n;
int i,j,k;
for (i=1;i<=m;i++)
{
cin>>cap[0][i];
}
int lastedge[1003]={0};
int fromsource = 0;
for (i=1;i<=n;i++)
{
int a,b;
cin>>a;
for (j=1;j<=a;j++)
{
cin>>k;
if (lastedge[k] == 0)
{
firstedge[k] = 1000+i;
cap[k][1000+i] = inf;
lastedge[k] = 1000+i;
}
else if (lastedge[k] < 1000+i)
{
cap[lastedge[k]][1000+i] = inf;
lastedge[k] = 1000+i;
}
}
cin>>b;
cap[1000+i][1101] = b;
fromsource += b;
}
while ((j=maxflow(0,fromsource)) > 0)
{
ans += j;
for (i=0;i<=m;i++)
mem[i] = 0;
for (i=1001;i<=1000+n;i++)
mem[i] = 0;
mem[1101] = 0;
}
cout<<ans<<endl;
return 0;
}