POJ 1149 PIGS

Source: Internet
Author: User

POJ_1149

I am confused about this question. Let's take a look at this blog.

Http://imlazy.ycool.com/post.2059102.html

#include<stdio.h>
#include<string.h>
#define MAXD 110
#define MAXM 30010
#define MAXm 1010
#define INF 10000000
int N, M, S, T, e, first[MAXD], work[MAXD], next[MAXM], v[MAXM], flow[MAXM], d[MAXD], q[MAXD];
int g[MAXD][MAXD], pre[MAXm], cow[MAXm];
void add(int x, int y, int z)
{
v[e] = y;
flow[e] = z;
next[e] = first[x];
first[x] = e;
e ++;
}
void init()
{
int i, j, k, n;
e = 0;
S = 0, T = N + 1;
memset(first, -1, sizeof(first));
memset(g, 0, sizeof(g));
memset(pre, 0, sizeof(pre));
for(i = 1; i <= M; i ++)
scanf("%d", &cow[i]);
for(i = 1; i <= N; i ++)
{
scanf("%d", &n);
for(j = 0; j < n; j ++)
{
scanf("%d", &k);
if(k > M)
continue;
if(!pre[k])
g[0][i] += cow[k];
else
g[pre[k]][i] = 1;
pre[k] = i;
}
scanf("%d", &k);
add(i, T, k);
add(T, i, 0);
}
for(i = 1; i <= N; i ++)
if(g[0][i])
{
add(0, i, g[0][i]);
add(i, 0, 0);
}
for(i = 1; i <= N; i ++)
for(j = i + 1; j <= N; j ++)
if(g[i][j])
{
add(i, j, INF);
add(j, i, 0);
}
}
int bfs()
{
int i, j, k, rear = 0;
memset(d, -1, sizeof(d));
d[S] = 0;
q[rear ++] = S;
for(i = 0; i < rear; i ++)
for(j = first[q[i]]; j != -1; j = next[j])
if(flow[j] > 0 && d[v[j]] == -1)
{
d[v[j]] = d[q[i]] + 1;
if(v[j] == T)
return 1;
q[rear ++] = v[j];
}
return 0;
}
int dfs(int cur, int a)
{
if(cur == T)
return a;
for(int &i = work[cur]; i != -1; i = next[i])
if(flow[i] > 0 && d[v[i]] == d[cur] + 1)
if(int t = dfs(v[i], a < flow[i] ? a : flow[i]))
{
flow[i] -= t;
flow[i ^ 1] += t;
return t;
}
return 0;
}
void solve()
{
int i, j, k, t, cnt = 0;
while(bfs())
{
memcpy(work, first, sizeof(first));
while(t = dfs(S, INF))
cnt += t;
}
printf("%d\n", cnt);
}
int main()
{
while(scanf("%d%d", &M, &N) == 2)
{
init();
solve();
}
return 0;
}


Related Keywords:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.