Cod sursa(job #2662046)

Utilizator PatrickCplusplusPatrick Kristian Ondreovici PatrickCplusplus Data 23 octombrie 2020 13:03:37
Problema Felinare Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.15 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 9000, inf = 1e9;
int n, m, e, match[nmax], dist[nmax], pot[nmax];
vector <int> G[nmax * 2];
bool bfs(){
    queue <int> coada;
    for (int i = 1; i <= n; ++i){
        dist[i] = inf;
        if (match[i] == 0 && pot[i] == 0){
            coada.push(i);
            dist[i] = 0;
        }
    }
    dist[0] = inf;
    while (!coada.empty()){
        int nod = coada.front();
        coada.pop();
        if (nod != 0){
            for (auto it : G[nod]){
                if (pot[match[it]] == 1) continue;
                if (dist[match[it]] == inf){
                    dist[match[it]] = 1 + dist[nod];
                    coada.push(match[it]);
                }
            }
        }
    }
    return dist[0] != inf;
}

bool dfs(int nod){
    if (nod){
        for (auto it : G[nod]){
            if (pot[match[it]] == 1) continue;
            if (1 + dist[nod] == dist[match[it]] && dfs(match[it])){
                match[nod] = it;
                match[it] = nod;
                return true;
            }
        }
        return false;
    }
    return true;
}


int hopcroftKarp(){
    memset(match, 0, sizeof match);
    int cuplaj = 0;
    while (bfs()){
        for (int i = 1; i <= n; ++i){
            if (match[i] == 0 && dfs(i)){
                ++cuplaj;
            }
        }
    }
    return cuplaj;
}

int main(){
    fin >> n >> m;

    for (int i = 1; i <= m; ++i){
        int x, y;
        fin >> x >> y;
        G[x].push_back(y + n);
        G[y + n].push_back(x);
    }
    int contor = 0;
    int cuplaj = hopcroftKarp();
    for (int i = 1; i <= n; ++i){
        pot[i] = 1;
        int cuplaj_nou = hopcroftKarp();
        if (cuplaj_nou + 1 == cuplaj){
            cuplaj = cuplaj_nou;
            ++contor;
        }
        else{
            pot[i] = 0;
        }
    }
    for (int i = 1; i <= n; ++i){
        if (match[i + n] == 0){
            ++contor;
        }
    }
    fout << contor;
    fin.close();
    fout.close();
    return 0;
}