Cod sursa(job #1236098)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 1 octombrie 2014 14:20:12
Problema Cuplaj maxim in graf bipartit Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.48 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "cuplaj.in";
const char outfile[] = "cuplaj.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int oo = 0x3f3f3f3f;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

class BipartiteGraph {
public:
    BipartiteGraph() {
    }
    BipartiteGraph(int _N) {
        adj.resize(_N + 1);
        N = _N;
        match.resize(_N + 1);
        _pair.resize(_N + 1);
        used.resize(_N + 1);
    }
    void addEdge(int x, int y) {
        adj[x].push_back(y);
    }
    bool pairUp(int node) {
        if(used[node])
            return false;
        used[node] = true;
        for(It it = adj[node].begin(), fin = adj[node].end(); it != fin ; ++ it)
            if(!_pair[*it] || pairUp(_pair[*it])) {
                _pair[*it] = node;
                match[node] = *it;
                return true;
            }
        return false;

    }
    vector <pair<int, int> > getMaxMatching() {
        for(bool change = true ; change ; ) {
            change = false;
            fill(used.begin(), used.end(), 0);
            for(int i = 1 ; i <= N ; ++ i)
                if(!match[i] && pairUp(i))
                    change = true;
        }
        vector <pair<int, int> > ans;
        for(int i = 1 ; i <= N ; ++ i)
            if(match[i])
                ans.push_back(make_pair(i, match[i]));
        return ans;
    }
private:
    vector <vector <int> > adj;
    vector <bool> used;
    vector <int> _pair, match;
    int N;
};

int N, M, cnt;

int main() {
    fin >> N >> M >> cnt;
    BipartiteGraph G(N);
    for(int i = 1 ; i <= cnt ; ++ i) {
        int x, y;
        fin >> x >> y;
        G.addEdge(x, y);
    }
    vector <pair<int, int> > ans = G.getMaxMatching();
    fout << ans.size() << '\n';
    for(auto it : ans)
        fout << it.first << ' ' << it.second << '\n';

    fin.close();
    fout.close();
    return 0;
}