Cod sursa(job #3214775)

Utilizator matei__bBenchea Matei matei__b Data 14 martie 2024 13:54:25
Problema Cuplaj maxim in graf bipartit Scor 24
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define chad char
#define mod 5000011
#define dim 100005
#define lim 1000000
#define INF 1000000000
#define FOR(i,a,b) for(int i=(a); i<=(b); i++)
#define piii pair<int,pair<int,int> > 
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pb push_back
#define mp make_pair
#define nr_biti __builtin_popcount
using namespace std;
 
ifstream fin("cuplaj.in");    
ofstream fout("cuplaj.out"); 

int n1,n2,m;
vector<int> g[dim];
int st[dim]; // corespondentul din A al lui i 
int dr[dim]; // corespondentul din B al lui i
bool viz[dim];

bool dfs(int nod)
{
    if(viz[nod])
        return 0;

    viz[nod]=1;

    for(auto it:g[nod])
    {
        if(!st[it])
        {
            st[it]=nod;
            dr[nod]=it;
            return 1;
        }
    }

    for(auto it:g[nod])
    {
        if(dfs(dr[it]))
        {
            st[it]=nod;
            dr[nod]=it;
            return 1;
        }
    }

    return 0;
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr); 

    fin >> n1 >> n2 >> m;

    for(int i=1; i<=m; i++)
    {
        int x,y;

        fin >> x >> y;

        g[x].pb(y);
    }

    int ans=0;

    while(1)
    {
        bool sch=0;

        for(int i=1; i<=n1; i++)
            viz[i]=0;

        for(int i=1; i<=n1; i++)
        {
            if(dr[i]==0 && dfs(i))
            {
                sch=1;
                ans++;
            }
        }

        if(!sch)
            break;
    }

    fout << ans << "\n";

    for(int i=1; i<=n1; i++)
        if(dr[i])
            fout << i << " " << dr[i] << "\n";
    
    return 0;
}