Cod sursa(job #3182876)

Utilizator AndreiKatsukiAndrei Dogarel AndreiKatsuki Data 10 decembrie 2023 00:16:52
Problema Taramul Nicaieri Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("harta.in");
ofstream g("harta.out");

const int NMAX = 205;
int n, capacity[NMAX][NMAX], flux[NMAX][NMAX], nrMuchii, parent[NMAX];
vector<int> Graph[NMAX];


int bfs(int s, int t){
    for(int i = 0; i <= t; ++i){
        parent[i] = -1;
    }
    parent[s] = -2;
    queue<pair<int, int>> q;
    q.push({s, INT_MAX});
    while(!q.empty()){
        int curr = q.front().first;
        int flow = q.front().second;
        q.pop();
        for(int next : Graph[curr]){
            if(parent[next] == -1 && capacity[curr][next] > flux[curr][next]){
                parent[next] = curr;
                int new_flow = min(flow, capacity[curr][next] - flux[curr][next]);
                if(next == t){
                    return new_flow;
                }
                q.push({next, new_flow});
            }
        }
    }
    return 0;
}


int maxFlow(int s, int t){
    int flow = 0;
    while(true){
        int new_flow = bfs(s, t);
        cout << new_flow << " ";
        if(new_flow == 0){
            break;
        }
        flow += new_flow;
        int curr = t;
        while(curr != s){
            int prev = parent[curr];
            flux[prev][curr] += new_flow;
            flux[curr][prev] -= new_flow;
            curr = prev;
        }
    }
    return flow;
}

int main(){
    f >> n;
    int s = 0, t = 2 * n + 1;
    for(int i = 1; i <= n; ++i){
        int x, y;
        f >> x >> y;
        nrMuchii += x;
        for(int j = 1; j <= n; ++j){
            if(j != i){
                Graph[i].push_back(j + n);
                Graph[j + n].push_back(i);
                capacity[i][j + n] = 1;
            }
        }
        Graph[s].push_back(i);
        Graph[i].push_back(s);
        capacity[s][i] = x;
        Graph[i + n].push_back(t);
        Graph[t].push_back(i + n);
        capacity[i + n][t] = y;
    }
    maxFlow(s, t);
    g << nrMuchii << "\n";
    for(int i = 1; i <= n; ++i){
        for(int j = n + 1; j < t; ++j){
            if(flux[i][j]){
                g << i << " " << j - n << "\n";
            }
        }
    }
    return 0;
}