Cod sursa(job #3324671)

Utilizator Mihai_OctMihai Octavian Mihai_Oct Data 22 noiembrie 2025 21:32:42
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("cmcm.in");
ofstream fout("cmcm.out");
const int MAX = 1e9;
struct Muchie {
    int y, c;
};
int n, m, mch, i, j, surs, dest, rasp;
int flux[602][602];
int idx[602][602];
int ant[602], cost[602];
vector<Muchie> gr[602];
set<int> parte;
bool viz[602];

static inline bool Dijkstra(int surs, int dest) {
    for(int i = surs; i <= dest; i++) cost[i] = MAX;
    memset(viz, false, sizeof(viz));
    queue<int> q;

    cost[surs] = 0;
    viz[surs] = true;

    q.push(surs);

    while(!q.empty()) {
        int nod = q.front();
        q.pop();

        viz[nod] = false;
        for(Muchie urm : gr[nod]) {
            int costNou = urm.c + cost[nod];
            if(costNou < cost[urm.y] && flux[nod][urm.y] > 0) {
                cost[urm.y] = costNou;
                ant[urm.y] = nod;

                if(!viz[urm.y]) {
                    viz[urm.y] = true;
                    q.push(urm.y);
                }
            }
        }
    }

    return cost[dest] != MAX;
}

static inline void Reverse(int surs, int dest) {
    int poz = dest;

    while(poz != surs) {
        flux[ant[poz]][poz]--;
        flux[poz][ant[poz]]++;

        int i = idx[ant[poz]][poz];
        if(i > 0) parte.insert(i);
        else      parte.erase(-i);

        poz = ant[poz];
    }
    rasp += cost[dest];
}

int main() {
    //ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr);

    fin >> n >> m >> mch;

    surs = 0;
    dest = n + m + 1;

    for(i = 1; i <= mch; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        y += n;
        gr[x].push_back({y,  c});
        gr[y].push_back({x, -c});

        idx[x][y] =  i;
        idx[y][x] = -i;

        flux[x][y] = 1;
    }

    for(i = 1; i <= n; i++) {
        gr[surs].push_back({i, 0});
        gr[i].push_back({surs, 0});
        flux[surs][i] = 1;
    }
    for(i = n + 1; i <= n + m; i++) {
        gr[i].push_back({dest, 0});
        gr[dest].push_back({i, 0});
        flux[i][dest] = 1;
    }

    while(Dijkstra(surs, dest)) Reverse(surs, dest);
    fout << parte.size() << " " << rasp << "\n";
    for(int cur : parte) fout << cur << " ";

    return 0;
}