Cod sursa(job #1428946)

Utilizator DEFINEtelyEngineersUPB Pirtoaca Vasilescu Zamfiratos DEFINEtelyEngineers Data 5 mai 2015 12:49:38
Problema Cc Scor 100
Compilator cpp Status done
Runda acm_practice2 Marime 2.22 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

#define Nmax 210
#define source 205
#define destination 206
#define offset 100
#define inf 0x3f3f3f3f

std::ifstream in("cc.in");
std::ofstream out("cc.out");

std::vector<std::pair<int, int> > G[Nmax];
int C[Nmax][Nmax], F[Nmax][Nmax], T[Nmax];

bool dijkstra(int &dist) {

    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int> >, std::greater<std::pair<int, int> > > PQ;
    std::vector<int> D(Nmax, inf);

    PQ.push(std::make_pair(0, source));
    D[source] = 0;

    while (!PQ.empty()) {
        int node = PQ.top().second;
        int c = PQ.top().first;

        PQ.pop();
        if (c != D[node]) continue;

        for (int i = 0; i < G[node].size(); i++) {
            int nextNode = G[node][i].first;
            int cost = G[node][i].second;

            if (C[node][nextNode] == F[node][nextNode]) continue;

            if (D[node] + cost < D[nextNode]) {
                D[nextNode] = D[node] + cost;
                PQ.push(std::make_pair(D[nextNode], nextNode));
                T[nextNode] = node;

                if (nextNode == destination) {
                    dist = D[nextNode];
                    return true;
                }
            }
        }
    }

    return false;
}

int main() {
    int N;
    in >> N;

    for (int i = 1; i <= N; i++) {
        G[source].push_back(std::make_pair(i, 0));
        G[i].push_back(std::make_pair(source, 0));
        C[source][i] = 1;

        G[i + offset].push_back(std::make_pair(destination, 0));
        G[destination].push_back(std::make_pair(i + offset, 0));
        C[i + offset][destination] = 1;
    }

    for (int i = 1; i <= N; i++)
        for (int j = 1; j <= N; j++) {
            int x;
            in >> x;

            G[i].push_back(std::make_pair(j + offset, x));
            G[j + offset].push_back(std::make_pair(i, -x));
            C[i][j + offset] = 1;
        }

    int dist = 0, total = 0;
    while (dijkstra(dist)) {

        int node = destination;

        while (node != source) {
            F[T[node]][node] ++;
            F[node][T[node]] --;

            node = T[node];
        }

        total += dist;
    }

    out << total << "\n";
}