Cod sursa(job #2833645)

Utilizator DordeDorde Matei Dorde Data 15 ianuarie 2022 14:18:39
Problema Felinare Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.24 kb
#include<bits/stdc++.h>
#define inf INT_MAX
using namespace std;
ifstream fin("felinare.in");
ofstream fout("felinare.out");
int const N = 2e4 + 3;
int n , m , a , b;
vector<int> v[N];
queue<int> q;
int lv[N];
int st[N] , dr[N];
bool bfs(){
    for(int i = 1 ; i <= n ; ++ i)
        if(!dr[i])
            q.push(i) , lv[i] = 0;
        else
            lv[i] = inf;///nod cuplat [i dr[y]]
    lv[0] = inf;///nodurile necuplate sunt cuplate cu 0
    while(!q.empty()){
        auto x = q.front();
        q.pop();
        if(lv[x] < lv[0]){///daca il cuplez pe 0 cu cineva inseamna ca am gasit cuplaj din lant de lungime minimia, nu are rost sa caut mai adanc
            for(auto y : v[x]){
                ///ma duc pe muchia [x , y] NECUPLATA
                ///verific daca y e cuplat
                if(lv[st[y]] == inf){///y e cuplat cu st[y]
                    lv[st[y]] = 1 + lv[x];///[x , y] , [y , st[y]] , ...
                    q.push(st[y]);
                }
            }
        }
    }
    return lv[0] != inf;///am gasit minim un lant alternant
}
bool dfs(int x){
    if(x != 0){///
        for(auto y : v[x]){
            if(1 + lv[x] == lv[st[y]] && dfs(st[y])){
                ///lv[x] + 1 == lv[st[y]] => [x , y] necuplat , [y , st[y]] cuplat
                ///daca dfs(st[y]) => [st[y] , w] cuplat , [x , y] cuplat
                st[y] = x;
                dr[x] = y;
                return true;
            }
        }
        lv[x] = inf;///nu am gasit cuplaj, marchez pentru a nu verifica pe viitor?
        return false;
    }
    ///x == 0 => am gasit nod necuplat, si am refacut cuplajul ca sa-l cuplez cu nodul care a apelat
    return true;
}
int maxmatch(){
    fill(st , st + N , 0);
    fill(dr , dr + N , 0);
    int r = 0;
    while(bfs()){
        for(int i = 1 ; i <= n ; ++ i){
            if(!dr[i] && dfs(i)){
                ++ r;
            }
        }
    }
    return r;
}
int main()
{
    fin >> n >> m;
    for(int i = 1 ; i <= m ; ++ i){
        fin >> a >> b;
        v[a].push_back(b + n);
    }
    maxmatch();
    int ans = n + n;
    for(int i = 1 ; i <= n ; ++ i)
        if(dr[i] != 0)
            -- ans;
    fout << ans << '\n';
    return 0;
}