Cod sursa(job #2715098)

Utilizator adiaioanaAdia R. adiaioana Data 2 martie 2021 23:22:01
Problema Cc Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.76 kb
#include <fstream>
#include <queue>
#include <vector>
#define LL long long
using namespace std;
ifstream cin("cc.in");
ofstream cout("cc.out");
///de abia terminasem debug la cmcm si uite, cmcm
priority_queue <pair<LL,int>, vector < pair<LL,int> >, greater < pair < LL,int > >  >pq;
int N, S, D, viz[300], ant[300];
LL fl[300][300],Fm,Fcst, Cst[300][300], d[300], real_d[300], old_d[300];
vector <int> G[300];
long long inf=120000000;
queue <int> q;


inline void scan();
inline void fordfiesta();
bool daicstra();

int main()
{
    scan();
    fordfiesta();
    while(daicstra());
    cout<<Fcst<<'\n';
    return 0;
}

inline void scan()
{
    cin>>N;S=0; D=2*N+1;

    for(int i=1; i<=N; ++i){
        for(int j=N+1; j<=2*N; ++j)
        {
            fl[i][j]=1;
            G[i].push_back(j);
            G[j].push_back(i);

            cin>>Cst[i][j];
            Cst[j][i]=-Cst[i][j];
        }
        fl[S][i]=1;
        fl[i+N][D]=1;
        G[S].push_back(i);
        G[i+N].push_back(D);
    }
}

inline void fordfiesta()
{
    int nod; LL new_d;
    for(int i=0; i<=201; ++i) old_d[i]=inf;
    viz[S]=1;
    q.push(S);
    while(!q.empty())
    {
        nod=q.front(); q.pop();
        viz[nod]=0;
        if(nod==D)
            continue;
        for(auto nn:G[nod])
            if(fl[nod][nn])
            {
                new_d=old_d[nod]+Cst[nod][nn];
                if(new_d<old_d[nn])
                {
                    old_d[nn]=new_d;
                    if(!viz[nn])
                    {
                        q.push(nn);
                        viz[nn]=1;
                    }
                }
            }
    }
}

bool daicstra()
{
    for(int i=S; i<=D; ++i)
        d[i]=inf;
    d[S]=0; real_d[S]=0;
    pq.push({0,S});
    int nod;
    LL cost, new_d;
    while(!pq.empty())
    {
        nod=pq.top().second;
        cost=pq.top().first;
        pq.pop();
        if(cost!=d[nod])
            continue;
        for(auto nn : G[nod])
            if(fl[nod][nn])
            {
                new_d=d[nod]+old_d[nod]-old_d[nn]+Cst[nod][nn];
                if(new_d<d[nn])
                {
                    d[nn]=new_d;
                    ant[nn]=nod;
                    real_d[nn]=real_d[nod]+Cst[nod][nn];
                    pq.push({d[nn],nn});
                }
            }
    }
    if(d[D]==inf)
        return 0;
    long long Fmin=inf, total=0;
    for(nod=D; nod!=S; nod=ant[nod])
    {
        Fmin=min(Fmin, 1ll*fl[ant[nod]][nod]);
        total+=Cst[ant[nod]][nod];
    }
    Fm+=Fmin;
    Fcst+=total*Fmin;
    for(nod=D; nod!=S; nod=ant[nod])
    {
        fl[ant[nod]][nod]-=Fmin;
        fl[nod][ant[nod]]+=Fmin;
    }
    return 1;

}