Cod sursa(job #1596473)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 11 februarie 2016 00:33:16
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <algorithm>
#include <bitset>
#include <vector>
#include <array>
using namespace std;
 
constexpr int maxn = 10010;
 
vector<int> graf[maxn];
int st[maxn], dr[maxn];
bitset<maxn> tried;
 
static bool try_to_repair(const int x){
    if(tried[x]){
        return false; }
    tried[x] = true;
    for(const auto y : graf[x]){
        if(st[y] == -1){
            dr[x] = y;
            st[y] = x;
            return true; } }
    for(const auto y : graf[x]){
        if(try_to_repair(st[y])){
            dr[x] = y;
            st[y] = x;
            return true; } }
    return false; }
 
int main(){
    ifstream f("cuplaj.in");
    ofstream g("cuplaj.out");
    int n, m, e;
 
    f >> n >> m >> e;
 
    for(int i = 0, a, b; i < e; ++i){
        f >> a >> b;
        graf[a-1].push_back(b-1); }
    fill(begin(st), end(st), -1);
    fill(begin(dr), end(dr), -1);
 
    for(bool changed = true; changed; ){
        changed = false;
        tried.reset();
        for(int i = 0; i < n; ++i){
            if(dr[i] == -1){
                changed = changed || try_to_repair(i); } } }
 
    const int sz_cuplaj = count_if(begin(dr), begin(dr)+n, [](const int x){ return x != -1; });
    g << sz_cuplaj << endl;
    for(int i = 0; i < n; ++i){
        if(dr[i] != -1){
            g << i+1 << ' ' << dr[i]+1 << endl; } }
 
    return 0; }