Cod sursa(job #1315280)

Utilizator retrogradLucian Bicsi retrograd Data 12 ianuarie 2015 18:18:09
Problema Cuplaj maxim in graf bipartit Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.26 kb
#include<fstream>
#include<vector>
#include<cstring>

#define MAXN 10000

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

struct Edge{
    int val;
    bool a;
    Edge(int v, bool x) {val = v; a = x;}
    Edge(){}
};

vector<Edge> G[2*MAXN+5];

void remove (int b, int e) {
    int i;
    for(i=0; G[b][i].val!=e; i++);
    G[b][i].a = 0;
}
void add (int b, int e) {
    int i;
    for(i=0; G[b][i].val!=e; i++);
    G[b][i].a = 1;
}

bool VIZ[MAXN*2+5];
int PARENT[MAXN*2+5];
bool dfs(const int &s, const int &d) {
    if(s == d) return true;
    for(int i=0; i<G[s].size(); i++) {
        if(G[s][i].a && !VIZ[G[s][i].val]) {
            VIZ[G[s][i].val] = 1;
            PARENT[G[s][i].val] = s;
            if(dfs (G[s][i].val, d))
                return true;
        }
    }
    return false;
}

void maxflow(const int &s, const int &t) {
    while(dfs(s, t)) {
        for(int i=t; i!=s; i=PARENT[i]) {
            remove(PARENT[i], i);
            add(i, PARENT[i]);
        }
        memset(VIZ, 0, sizeof(VIZ));
    }
}

int m, n, e;

void afisgraf(const int &t) {/*
    for(int i=1; i<=n; i++) {
        fout<<"\nL["<<i<<"]: ";
        for(int j=0; j<G[i].size(); j++) {
            if(G[i][j].a) fout<<G[i][j].val-MAXN<<" ";
        }
    }*/
    for(int i=0; i<G[t].size(); i++)
        if(G[t][i].a) {
            int nod = G[t][i].val;
        //fout<<"\nR["<<i-MAXN<<"]: ";
        for(int j=0; j<G[nod].size(); j++) {
            if(G[nod][j].a) fout<<G[nod][j].val<<" "<<nod-MAXN<<'\n';
        }
    }
}


int main() {
    fin>>n>>m>>e;
    int a, b;
    const int s = 0, t = 2*MAXN+1;
    while(e--) {
        fin>>a>>b;
        G[a].push_back(Edge(b+MAXN, 1));
        G[b+MAXN].push_back(Edge(a, 0));
    }
    for(int i=1; i<=n; i++) {
        G[0].push_back(Edge(i, 1));
        G[i].push_back(Edge(0, 0));
    }
    for(int i=1; i<=m; i++) {
        G[i+MAXN].push_back(Edge(t, 1));
        G[t].push_back(Edge(i+MAXN, 0));
    }

    //afisgraf();

    maxflow(s, t);

    //afisgraf();

    int sum = 0;
    int node;
    int i, j;
    for(i=0; i<G[t].size(); i++) {
        sum+=G[t][i].a;
    }fout<<sum<<'\n';
    afisgraf(t);
    return 0;
}