Cod sursa(job #2696390)

Utilizator bogdan.gusuleacGusuleac Bogdan bogdan.gusuleac Data 15 ianuarie 2021 19:48:13
Problema Cuplaj maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.6 kb
#include<fstream>
#include<vector>
#include<queue>

#define MAXSIZE 710
#define INF (1<<30)

using namespace std;

ofstream fout("cmcm.out");
ifstream fin("cmcm.in");

int n,m,source,destination,sol;
int cost[MAXSIZE][MAXSIZE],capacity[MAXSIZE][MAXSIZE],edge[MAXSIZE][MAXSIZE],flux[MAXSIZE][MAXSIZE],DIST[MAXSIZE];
short TT[MAXSIZE];

vector<short> G[MAXSIZE];
queue<short> Q;

bool used[MAXSIZE];

void read()
{
    int x,y,edges,c;
    fin>>n>>m>>edges;
    for(int i=1; i<=edges; i++)
    {
        fin>>x>>y>>c;
        y+=n;
        G[x].push_back(y);
        G[y].push_back(x);
        cost[x][y]=c;
        cost[y][x]=-c;
        capacity[x][y]=1;
        edge[x][y]=i;
    }
}
void print()
{
    int i,j,c=0;
    for(i=1; i<=n; i++)
        for(j=n+1; j<destination; j++)
            if(capacity[i][j] && flux[i][j])
            {
                c++;
                break;
            }
    fout<<c<<' '<<sol<<'\n';
    for(i=1; i<=n; i++)
        for(j=n+1; j<destination; j++)
            if(capacity[i][j] && flux[i][j])
            {
                fout<<edge[i][j]<<' ';
                break;
            }
}
void prepare()
{
    destination=n+m+1;
    for(int i=1; i<=n; i++)
    {
        G[i].push_back(source);
        G[source].push_back(i);
        capacity[source][i]=1;
    }
    for(int i=n+1; i<=n+m; i++)
    {
        G[i].push_back(destination);
        G[destination].push_back(i);
        capacity[i][destination]=1;
    }
}
void INIT()
{
    for(int i=0; i<=destination; i++)
    {
        DIST[i]=INF;
        TT[i]=-1;
    }
}
bool bellman_ford()
{
    short nod,vec;
    INIT();
    Q.push(source);
    used[source]=1;
    DIST[source]=0;
    while(!Q.empty())
    {
        nod=Q.front();
        Q.pop();
        for(size_t i=0; i<G[nod].size(); i++)
        {
            vec=G[nod][i];
            if(capacity[nod][vec]>flux[nod][vec] && DIST[nod]+cost[nod][vec]<DIST[vec])
            {
                DIST[vec]=DIST[nod]+cost[nod][vec];
                TT[vec]=nod;
                if(!used[vec])
                {
                    used[vec]=1;
                    Q.push(vec);
                }
            }
        }
        used[nod]=0;
    }
    return (DIST[destination]!=INF);
}
int main()
{
    read();
    prepare();
    while(bellman_ford())
    {
        for(int i=destination; i!=source; i=TT[i])
        {
            flux[TT[i]][i]++;
            flux[i][TT[i]]--;
        }
        sol+=DIST[destination];
    }
    print();
    fin.close();
    fout.close();
    return 0;
}