Cod sursa(job #1744908)

Utilizator fanache99Constantin-Buliga Stefan fanache99 Data 20 august 2016 18:34:55
Problema Paznici2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.56 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

ifstream cin("paznici2.in");
ofstream cout("paznici2.out");

const int MAXN = 420;
const int INF = 1000000000;

int n, sink, source;
int capacity[MAXN][MAXN], cost[MAXN][MAXN], dad[MAXN], best[MAXN];
bool inQueue[MAXN];
vector<pair<int, int> > g[MAXN];
vector<int> answer;
queue<int> Queue;

bool BellmanFord(int start) {
    for (int i = 0; i <= 2 * n + 1; i++)
        best[i] = INF;
    Queue.push(start);
    inQueue[start] = true;
    best[start] = 0;
    while (!Queue.empty()) {
        int node = Queue.front();
        Queue.pop();
        inQueue[node] = false;
        if (node == sink)
            continue;
        for (auto &nextNode : g[node])
            if (capacity[node][nextNode.first] && best[nextNode.first] > best[node] + nextNode.second) {
                best[nextNode.first] = best[node] + nextNode.second;
                dad[nextNode.first] = node;
                if (!inQueue[nextNode.first]) {
                    inQueue[nextNode.first] = true;
                    Queue.push(nextNode.first);
                }
            }
    }
    return best[sink] != INF;
}

int MaximumFlow() {
    int cost = 0;
    memset(inQueue, false, sizeof(inQueue));
    while (BellmanFord(source)) {
        cost += best[sink];
        for (int node = sink; node != source; node = dad[node]) {
            capacity[dad[node]][node]--;
            capacity[node][dad[node]]++;
        }
    }
    return cost;
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        g[0].push_back(make_pair(i, 0));
        g[i].push_back(make_pair(0, 0));
        capacity[0][i] = 1;
        for (int j = 1; j <= n; j++) {
            int x;
            cin >> x;
            g[i].push_back(make_pair(j + n, x));
            g[j + n].push_back(make_pair(i, -x));
            capacity[i][j + n] = 1;
            cost[i][j + n] = x;
        }
        g[i + n].push_back(make_pair(2 * n + 1, 0));
        g[2 * n + 1].push_back(make_pair(i + n, 0));
        capacity[i + n][2 * n + 1] = 1;
    }
    source = 0;
    sink = 2 * n + 1;
    cout << MaximumFlow() << "\n";
    for (int i = n + 1; i <= 2 * n; i++) {
        BellmanFord(i);
        answer.clear();
        for (int j = 1; j <= n; j++)
            if (best[j] == -cost[j][i])
                answer.push_back(j);
        cout << answer.size() << " ";
        for (auto &it : answer)
            cout << it << " ";
        cout << "\n";
    }
    return 0;
}