poj 1087 A Plug for UNIX(网络流最大流)

题意:房间里N个通了电的插座,有M种电器,每种电器只有插在对应类型的插座上才能正常工作。现在有K个转换器,能将一种类型的插座转换成另一种类型的插座。利用这K个转换器和N个通电插座,使尽量多的电器能够正常通电工作(题目要求输出最少能使多少台电器不工作的数目)。

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define MAX 500
int c[MAX][MAX],  pre[MAX], max_flow, que[10000];
char receptacle[MAX][25];
int edmonds_karp(int src, int des)
{
    int front, rear, v, i, visit[MAX];

    memset(visit, 0, sizeof(visit));
    front = rear = 0;
    que[rear++] = src;
    visit[src] = 1;

    while(front != rear)
    {
        v = que[front++];
        for(i=1; i<=des; i++)
        {
            if(!visit[i] && c[v][i])
            {
                que[rear++] = i;
                pre[i] = v;
                visit[i] = 1;
                if(i == des)
                    return 1;
            }
        }
    }
    return 0;
}
void ford_fulkerson(int src, int des)
{
    int x, y, tmp, min;
    max_flow = 0;
    while(edmonds_karp(src,des)!=0)
    {
        //printf("max_flow:%d\n",max_flow);
        min = MAX;
        x = pre[des];
        y = des;
        while(y!=src)
        {
            if(c[x][y]<min)
                min = c[x][y];
            tmp = x;
            x = pre[x];
            y = tmp;
        }
        max_flow += min;
        //update
        x = pre[des];
        y = des;
        while(y!=src)
        {
            c[x][y] -= min;
            c[y][x] += min;
            tmp = x;
            x = pre[x];
            y = tmp;
        }
    }
}
int main()
{
    char tmp1[25],tmp2[25];
    int tmp, i, j, n, m, k, x, y;

    memset(c,0,sizeof(c));
    scanf("%d",&n);
    for(i=1; i<=n; i++)
    {
        scanf("%s",receptacle[i]);
    }
    tmp = n;
    scanf("%d",&m);
    for(i=1; i<=m; i++)
    {
        scanf("%s %s",tmp1, tmp2);
        for(j=1; j<=n; j++)
            if(strcmp(receptacle[j],tmp2)==0)
                break;
        if(j>n)
        {
            n++;
            strcpy(receptacle[n],tmp2);
        }
        c[0][j]++; // 0 as src
    }
    scanf("%d",&k);
    for(i=1; i<=k; i++)
    {
        scanf("%s %s",tmp1,tmp2);
        for(j=1; j<=n; j++)
            if(strcmp(tmp1,receptacle[j])==0)
                break;
        if(j>n)
        {
            n++;
            strcpy(receptacle[n],tmp1);
        }
        x = j;

        for(j=1; j<=n; j++)
            if(strcmp(tmp2,receptacle[j])==0)
                break;
        if(j>n)
        {
            n++;
            strcpy(receptacle[n],tmp2);
        }
        y=j;

        c[x][y] = MAX;
    }
    for(i=1; i<=tmp; i++)
        c[i][n+1] = 1;
    ford_fulkerson(0,n+1);
    printf("%d\n",m-max_flow);
    return 0;
}

你可能感兴趣的:(poj 1087 A Plug for UNIX(网络流最大流))