Cod sursa(job #2419114)

Utilizator Leonard1998Olariu Leonard Leonard1998 Data 7 mai 2019 17:58:34
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>
#define MAXN 10005

using namespace std;

int N, M, edgeCount; //N - left size, M - right size
vector<int> G[MAXN];
int matchRightPartition[MAXN], matchLeftPartition[MAXN], visited[MAXN];

int pairUp(int currNode) {
    visited[currNode] = 1;

    int possibleMatchCount = G[currNode].size();
    int rightMatch;

    for (int i = 0; i < possibleMatchCount; ++i) {
        rightMatch = G[currNode][i];

        if (!matchLeftPartition[rightMatch]) {
            matchRightPartition[currNode] = rightMatch;
            matchLeftPartition[rightMatch] = currNode;
            return 1;
        }
    }

    for (int i = 0; i < possibleMatchCount; ++i) {
        rightMatch = G[currNode][i];

        if (!visited[matchLeftPartition[rightMatch]] && pairUp(matchLeftPartition[rightMatch])) {
            matchRightPartition[currNode] = rightMatch;
            matchLeftPartition[rightMatch] = currNode;
            return 1;
        }
    }

    return 0;
}

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

    scanf("%d %d %d", &N, &M, &edgeCount);

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

    for (int change = 1; change;) {
        change = 0;
        memset(visited, 0, sizeof(visited));
        for (int i = 1; i <= N; ++i)
            if (!matchRightPartition[i]) change |= pairUp(i);
    }

    int cuplaj = 0;
    for (int i = 1; i <= N; ++i)
        if (matchRightPartition[i]) cuplaj += (matchRightPartition[i] > 0);
    printf("%d\n", cuplaj);

    for (int i = 1; i <= N; ++i)
        if (matchRightPartition[i]) printf("%d %d\n", i, matchRightPartition[i]);

    return 0;
}