Cod sursa(job #2958613)

Utilizator Katherine456719Swan Katherine Katherine456719 Data 27 decembrie 2022 11:47:53
Problema Taramul Nicaieri Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.39 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

int n;
vector<vector<int>>muchii;
vector<pair<int,int>> grade;
int cp[205][205];
vector<int> parinte;
bool gaseste_drum(){
    parinte = vector <int>(2*n+2,-1);
    queue <pair<int,int>>q;
    int node,curr_cp;
    parinte[0] = -2;
    q.push({0,999999});
    while(!q.empty()){
        node = q.front().first,
        curr_cp = q.front().second;
        q.pop();
        if(node != 2*n + 1) {
            for (auto i: muchii[node]) {
                if (parinte[i] == -1 and cp[node][i] > 0) {
                    q.push({i,min(curr_cp,cp[node][i])});
                    parinte[i] = node;
                }
            }
        }

    }
    return parinte[2*n+1] != -1;
}
int main() {
    ifstream fin("harta.in");
    ofstream fout("harta.out");
    fin >> n;
    muchii.resize(2*n+2);
    int x,y;
    grade.push_back({0,n});
    while(fin >> x >> y)
        grade.push_back({x,y});
    for(int i = 1;i <= n; ++i)
        for(int j = n + 1; j <= n*2; ++j){
            if(i + n!= j) {
                muchii[i].push_back(j);
                muchii[j].push_back(i);
                cp[i][j]++;
            }
        }
    for(int i = 1;i <= n; ++i){
            muchii[0].push_back(i);
            cp[0][i] = grade[i].first;
    }
    for(int j = n + 1; j <= n*2; ++j) {
        muchii[j].push_back(2*n+1);
        muchii[2*n+1].push_back(j);
        cp[j][2*n+1] = grade[j-n].second;
    }
    int ans = 0;
    while(gaseste_drum()){
        for (auto x: muchii[2*n+1]){
            if(parinte[x] != -1){
                int flux = 9999999;
                int node = 2*n+1;
                parinte[2*n+1] = x;
                while(node != 0){
                    flux = min(flux,cp[parinte[node]][node]);
                    node = parinte[node];
                }
                node = 2*n+1;
                while(node != 0){
                    cp[node][parinte[node]] +=flux;
                    cp[parinte[node]][node] -=flux;
                    node = parinte[node];
                }
                ans += flux;
            }
        }
    }
    fout << ans <<"\n";
    for(int i=1;i<=n;++i) {
        for (int j = n+1; j <= 2 * n; ++j)
            if(cp[i][j] == 0 and i + n!= j)
            fout << i << " " << j-n <<"\n";
    }
    return 0;
}