Cod sursa(job #1828972)

Utilizator antanaAntonia Boca antana Data 14 decembrie 2016 09:56:55
Problema Cuplaj maxim in graf bipartit Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb
#include <cstdio>
#include <vector>

#define MAXN 10001
#define INF 0x3f3f3f3f

using namespace std;

vector <int> G[MAXN];

int m, q[MAXN], p_u[MAXN], p_v[MAXN], dist[MAXN], u[MAXN], v[MAXN];
bool ok_u[MAXN], ok_v[MAXN];

inline bool bfs()
{
    int i, left = 0, right = 0, node, neigh;

    for(i=1; i<=u[0]; ++i)
        if(!p_u[i])
        {
            dist[u[i]] = 0;
            q[right++] = u[i];
        }
        else dist[u[i]] = INF;

    dist[0] = INF;
    while(left < right)
    {
        node = q[left++];
        if(dist[node] < dist[0])
        {
            for(i=G[node].size()-1; i>=0; --i)
            {
                neigh = G[node][i];
                if(dist[p_v[neigh]] == INF)
                {
                    dist[p_v[neigh]] = dist[node] + 1;
                    q[right++] = p_v[neigh];
                }
            }
        }
    }

    return dist[0] != INF;
}

bool dfs(int node)
{
    int i, neigh;

    if(node != 0)
    {
        for(i=G[node].size()-1; i>=0; --i)
        {
            neigh = G[node][i];
            if(dist[p_v[neigh]] == dist[node] + 1)
            {
                if(dfs(p_v[neigh]))
                {
                    p_u[node] = neigh;
                    p_v[neigh] = node;
                    return true;
                }
            }
        }
        dist[node] = INF;
        return false;
    }
    return true;
}

int hopcroft_karp()
{
    int i, ans = 0, node;

    for(i=1; i<=u[0]; ++i)
        p_u[u[i]] = 0;
    for(i=1; i<=v[0]; ++i)
        p_v[v[i]] = 0;

    while(bfs())
    {
        for(i=1; i<=u[0]; ++i)
        {
            node = u[i];
            if(p_u[node] == 0)
                if(dfs(node))
                    ans++;
        }
    }

    return ans;
}

int main()
{
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);

    int i, x, y, a = 0, b = 0;

    scanf("%d%d%d", &u[0], &v[0], &m);

    for(i=1; i<=m; ++i)
    {
        scanf("%d%d", &x, &y);
        G[x].push_back(y);

        if(!ok_u[x]) u[++a] = x, ok_u[x] = 1;
        if(!ok_v[y]) v[++b] = y, ok_v[y] = 1;
    }

    printf("%d\n", hopcroft_karp());

    for(i=1; i<=u[0]; ++i)
        if(p_u[u[i]] != 0)
            printf("%d %d\n", u[i], p_u[u[i]]);

    return 0;
}