Cod sursa(job #2448244)

Utilizator CharacterMeCharacter Me CharacterMe Data 16 august 2019 12:39:50
Problema Cc Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <bits/stdc++.h>
#define inf 2000000001
#define pii pair<int, int>
///N=100
///nr obiecte=200
///dist=10000
using namespace std;
int n, i, j, k, sol, s, d;
int now[205], then[205], dmin[205], last[205];
int flow[205][205], cost[205][205];
vector<int> graph[205];
priority_queue<pii, vector<pii>, greater<pii> > pq;
///
void read();
void solve();
void write();
bool dij();
int main()
{
    read();
    solve();
    write();
    return 0;
}
void read(){
    freopen("cc.in", "r", stdin);
    scanf("%d", &n);
    for(i=1; i<=n; ++i){
        for(j=1; j<=n; ++j){
            int c;
            scanf("%d", &c);
            cost[i][j+n]=c;
            cost[j+n][i]=-c;
            flow[i][j+n]=1;
            graph[i].push_back(j+n);
            graph[j+n].push_back(i);
        }
    }
    fclose(stdin);
}
void solve(){
    s=0; d=2*n+1;
    for(int i=1; i<=n; ++i){
        graph[s].push_back(i);
        graph[i].push_back(s);
        flow[s][i]=1;
        graph[i+n].push_back(d);
        graph[d].push_back(i+n);
        flow[i+n][d]=1;
    }
    while(dij()){
        int p, maxflow=inf;
        for(p=d; p!=s; p=last[p]) maxflow=min(maxflow, flow[last[p]][p]);
        for(p=d; p!=s; p=last[p]){
            flow[last[p]][p]-=maxflow;
            flow[p][last[p]]+=maxflow;
        }
        sol+=now[d];
    }
}
void write(){
    freopen("cc.out", "w", stdout);
    printf("%d", sol);
    fclose(stdout);
}
bool dij(){
    for(int i=s; i<=d; ++i) dmin[i]=inf, last[i]=-1;
    dmin[s]=now[s]=0;
    pq.push({0, s});
    while(!pq.empty()){
        int cst=pq.top().first, node=pq.top().second; pq.pop();
        if(node==d) continue;
        if(cst>dmin[node]) continue;
        for(auto next:graph[node]){
            if(!flow[node][next]) continue;
            int cnext=cst+cost[node][next]+then[node]-then[next];
            if(cnext<dmin[next]){
                dmin[next]=cnext;
                now[next]=now[node]+cost[node][next];
                last[next]=node;
                pq.push({cnext, next});
            }
        }
    }
    for(int i=s; i<=d; ++i) then[i]=now[i];
    return dmin[d]!=inf;
}