Cod sursa(job #1450939)

Utilizator MciprianMMciprianM MciprianM Data 15 iunie 2015 11:57:04
Problema Cuplaj maxim in graf bipartit Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>
#include <vector>
#include <cstring>
 
using namespace std;
 
static const int MAXN = 10009;
vector<int> G[MAXN];
int matchForL[MAXN];
int matchForR[MAXN];
bool u[MAXN];
int maxDist;
 
bool match_it(int who, int dist)
{
	if(dist > maxDist)	return false;
    int vec;
    bool success = false;
    u[who] = true;
    for(int i = 0, l = G[who].size(); i < l && !success; i++)
    {
        vec = G[who][i];
        if(vec != matchForL[who]) // edge is white and node was not used
        {
            if(!matchForR[vec]) //end of the ride
            {
                success = true;
            }
            else if(!u[matchForR[vec]])
            {
                success = match_it(matchForR[vec], dist + 2); //go black
            }
            if(success)
            {
                matchForL[who] = vec;
                matchForR[vec] = who;
            }
        }
    }
    return success;
}
 
int main()
{
    int n, m, e, x, y;
    ifstream f("cuplaj.in");
    f >> n >> m >> e;
    for(int i = 0; i < e; i++)
    {
        f >> x >> y;
        G[x].push_back(y);
    }
    f.close();
	maxDist = 1;
    bool ok = true;
    do
    {
        ok = false;
        memset(u, 0, sizeof u);
        for(int i = 1; i <= n; i++)
        {
            if(!matchForL[i])
            {
                ok = match_it(i, 0) || ok;
            }
        }
		maxDist += 2;
    } while(ok || (maxDist - 2) * (maxDist - 2) <= n);
    vector<pair<int, int> > ans;
    for(int i = 1; i <= n; i++)
    {
        if(matchForL[i])
        {
            ans.push_back(pair<int, int>(i, matchForL[i]));
        }
    }
    ofstream g("cuplaj.out");
    g << ans.size() << '\n';
    for(int i = 0, l = ans.size(); i < l; i++)
    {
        g << ans[i].first << ' ' << ans[i].second << '\n';
    }
    g.close();
    return 0;
}