Cod sursa(job #2905631)

Utilizator 100pCiornei Stefan 100p Data 22 mai 2022 19:41:47
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.83 kb
#include <bits/stdc++.h>
#define ull unsigned long long
#define FILES freopen("cuplaj.in","r",stdin);\
              freopen("cuplaj.out","w",stdout);
#define CMAX 15485863
#define fastio std::ios_base::sync_with_stdio(NULL),cin.tie(NULL),cout.tie(NULL);
#define mp make_pair
#define INF 1e18
#define mod 666013
#define ll long long
#define SMAX 65000000
#define MAX 1000000
#define pb push_back
#define add emplace_back
#define void inline void

using namespace std;
vector<int>v[MAX+5],v2[MAX+5],newgr[MAX+5], newgr2[MAX+5];
map<pair<int,int>,bool> Mp;
int n,m,ed,where[MAX+5];
bool check[MAX+5],here[MAX+5],check2[MAX+5],here2[MAX+5];
set<int>constr;
vector<pair<int,int>> ans;
bool bfs()
{
    queue<pair<int,int>>q;
    for(int i = 1; i <= n; ++i)
    {
        newgr[i].clear();
        here[i] = 0;
        if(!check[i])
            q.push(mp(i,0)),here[i] = 1;
    }
    for(int i = 1;i <= m; ++i)
        newgr2[i].clear(), here2[i] = 0;
    while(!q.empty())
    {
        int x = q.front().first, y = q.front().second;
        q.pop();
        if(y == 1) here2[x] = 1;
        else here[x] = 1;
        if(!check2[x] && y == 1)
        {
            constr.insert(x);
            continue;
        }
        if(!y)
        {
            for(auto i : v[x])
            {
                if(!here2[i] && Mp[ {x,i}])
                    newgr[x].add(i),newgr2[i].add(x),q.push(mp(i,1-y));
            }
        }
        else
        {
            for(auto i : v2[x])
            {
                if(!here[i])
                    newgr[x].add(i),newgr2[i].add(x),q.push(mp(i,1-y));
            }
        }
    }
    return constr.size() != 0;
}
bool ok;
void dfs(int x,int y,int z)
{

    if(!y) here2[x] = 1;
    else here[x] = 1;
    if(y == 1 && !check[x])
    {
        ans.add(mp(x,z));
        check[x] = 1, check2[z] = 1;
        ok = 1;
        return;
    }
    if(!y)
    {
        for(auto i : newgr2[x])
        {
            if(!here[i])
                dfs(i,1-y,z);
            Mp[ {x,i}]  = 0;
            v2[i].add(x);
            if(ok) return;
        }
    }
    else
    {
        for(auto i : newgr[x])
        {
            if(!here2[i])
                dfs(i,1-y,z);
            if(ok) return;
        }
    }
}
int main()
{
    fastio
    FILES
    cin >> n >> m >> ed;
    for(int i = 1; i <= ed; ++i)
    {
        int a,b;
        cin >> a >> b;
        Mp[ {a,b}] = 1;
        v[a].add(b);
    }
    while(bfs())
    {
        for(int i = 1; i <= n; ++i) here[i] = 0;
        for(int i = 1; i <= m; ++i) here2[i] = 0;
        for(auto i : constr){
            dfs(i,0,i);
            ok = 0;
        }
        constr.clear();
    }
    cout << ans.size() << '\n';
    for(auto i : ans)
        cout << i.first << ' ' << i.second << '\n';
}