Cod sursa(job #2736844)

Utilizator stefan.popescuPopescu Stefan stefan.popescu Data 3 aprilie 2021 23:58:55
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <bits/stdc++.h>
using namespace std;
#define SERVER 0
const string nameFile="cmcm";
ifstream in (nameFile+".in");
ofstream out(nameFile+".out");
typedef pair<int, int> Pii;
#if (SERVER)
    #define in cin
    #define out cout
#endif
const int nmax=6e2;
const int oo=1e9;
vector <int> muchii[nmax+2];
bool capacity[nmax+2][nmax+2];
int cost[nmax+2][nmax+2];
int indiceMuchie[nmax+2][nmax+2];
int n1, n2, m, x, y, z;
int parent[nmax+2];
int dp[nmax+2];
bool inQ[nmax+2];
int source=0, sink;
bool bellmanFord(){
    queue <int> q;
    fill(dp, dp+n1+n2+2, oo);
    dp[source]=0;
    q.push(source);
    inQ[source]=true;
    while(!q.empty()){
        int nod=q.front(); q.pop();
        inQ[nod]=false;
        for(auto &x:muchii[nod])
            if(capacity[nod][x]&&dp[x]>cost[nod][x]+dp[nod]){
                dp[x]=cost[nod][x]+dp[nod];
                parent[x]=nod;
                if(!inQ[x])
                    q.push(x), inQ[x]=true;
            }
    }
    return dp[sink]!=oo;
}
int nrMuchii, costMin;
void flow(){
    while(bellmanFord()){
        costMin+=dp[sink];
        ///daca bellman-ford zice da, evident fluxul e 1
        for(int nodAct=sink; nodAct!=source; nodAct=parent[nodAct])
            capacity[parent[nodAct]][nodAct]^=1, capacity[nodAct][parent[nodAct]]^=1;
    }
}
int main()
{
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    in>>n1>>n2>>m;
    sink=n1+n2+1;
    for(int i=1; i<=m; i++){
        in>>x>>y>>z;
        indiceMuchie[x][n1+y]=i;
        muchii[x].push_back(n1+y);
        muchii[n1+y].push_back(x);
        cost[x][n1+y]=z;
        cost[n1+y][x]=-z;
        capacity[x][n1+y]=1;
    }
    for(int i=1; i<=n1; i++)
        capacity[0][i]=1, muchii[0].push_back(i), muchii[i].push_back(0);
    for(int i=n1+1; i<=n2+n1; i++)
        capacity[i][n1+n2+1]=1, muchii[i].push_back(sink), muchii[sink].push_back(i);
    flow();

    vector <int> sol;
    for(int i=1; i<=n1; i++){
        for(auto &x:muchii[i])
            if(x!=0&&!capacity[i][x]){
                nrMuchii++;
                sol.push_back(indiceMuchie[i][x]);
                break;
            }
    }
    out<<nrMuchii<<" "<<costMin<<"\n";
    for(auto &x:sol)
        out<<x<<" ";
    return 0;
}