首页 > 代码库 > UVA 753 A Plug for UNIX

UVA 753 A Plug for UNIX

最大流解决 。

设置源点 0,连接所有设备(device) 。设备-插头 -汇点

#include <map>#include <set>#include <list>#include <cmath>#include <ctime>#include <deque>#include <stack>#include <queue>#include <cctype>#include <cstdio>#include <string>#include <vector>#include <climits>#include <cstdlib>#include <cstring>#include <iostream>#include <algorithm>#define LL long long#define PI 3.1415926535897932626using namespace std;int gcd(int a, int b) {return a % b == 0 ? b : gcd(b, a % b);}#define MAXN 330const int INF = 0x3f3f3f3f ;int N,M,K,src,tag;int p[MAXN];int flow[MAXN][MAXN],cap[MAXN][MAXN];int a[MAXN];map<string ,int > cz,deg;string str;void read(){    cin >> N;    int add = 0;    cz.clear(); deg.clear();    memset(cap,0,sizeof(cap));    for (int i = 1; i <= N; i++)    {        cin >> str;        cz[str] = i;    }    cin >> M;    for (int i = 1; i <= M; i++)    {        cin >> str;        deg[str] = i;        cap[0][i] += 1;        cin >> str;        int tmp = cz[str];        if (tmp == 0)//需要新的插座        {            add ++;            cz[str] = N + add;            tmp = N + add;        }        cap[i][tmp + M] += 1;    }    for (int i = M + 1; i <= M + N; i++)        cap[i][N + M + add + 1] += 1;    src = 0; tag = N + M + add + 1;    cin >> K;    while (K --)    {        cin >> str;        int tmp = cz[str];        cin >> str;        int res = cz[str];        cap[M + tmp][M + res] += INF;    }}int Edmonds_karp(){    memset(flow,0,sizeof(flow));    queue<int>q;    int ans = 0;    while (!q.empty()) q.pop();    while (true)    {        memset(a,0,sizeof(a));        a[src] = INF;        q.push(src);        while (!q.empty())        {            int u = q.front(); q.pop();            for (int v = 1; v <= tag; v++)                if (!a[v] && cap[u][v] > flow[u][v])            {                p[v] = u;                q.push(v);                a[v] = min (a[u],cap[u][v] - flow[u][v]);            }        }        if (a[tag] == 0) break;        for (int u = tag; u != src; u = p[u])        {            flow[p[u]][u] += a[tag];            flow[u][p[u]] -= a[tag];        }        ans += a[tag];    }    return ans;}int main(){    //freopen("sample.txt","r",stdin);    int T;    scanf("%d",&T);    while (T--)    {        read();        printf("%d\n",M - Edmonds_karp());        if (T) putchar(\n);    }    return 0;}

 

UVA 753 A Plug for UNIX