Pagini recente » Cod sursa (job #1472722) | Cod sursa (job #1488113) | Cod sursa (job #126529) | Cod sursa (job #2062334) | Cod sursa (job #1801910)
#include <algorithm>
#include <fstream>
#include <cstring>
#include <queue>
#define INF 10000000
#define DIM 750
using namespace std;
struct a {
int cst, tata, node;
a() {}
a(int _cst, int _node, int _tata) : cst(_cst), tata(_tata), node(_node) {}
bool operator< (const a & q) const {
return (cst > q.cst);
}
};
int cost[DIM][DIM], flow[DIM][DIM], c[DIM][DIM];
int n, D, tcost;
int t[DIM], dmin[DIM];
bool dijkstra();
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n) {
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
};
class OutParser {
private:
FILE *fout;
char *buff;
int sp;
void write_ch(char ch) {
if (sp == 50000) {
fwrite(buff, 1, 50000, fout);
sp = 0;
buff[sp++] = ch;
} else {
buff[sp++] = ch;
}
}
public:
OutParser(const char* name) {
fout = fopen(name, "w");
buff = new char[50000]();
sp = 0;
}
~OutParser() {
fwrite(buff, 1, sp, fout);
fclose(fout);
}
OutParser& operator << (int vu32) {
if (vu32 <= 9) {
write_ch(vu32 + '0');
} else {
(*this) << (vu32 / 10);
write_ch(vu32 % 10 + '0');
}
return *this;
}
OutParser& operator << (char ch) {
write_ch(ch);
return *this;
}
OutParser& operator << (const char *ch) {
while (*ch) {
write_ch(*ch);
++ch;
}
return *this;
}
};
int main() {
InParser f ("cc.in");
OutParser g ("cc.out");
f >> n;
D = 2 * n + 2;
for (int i = n + 2; i < 2 * n + 2; ++i) {
flow[i][2 * n + 2] = 1;
cost[i][2 * n + 2] = 0;
}
for (int i = 2; i <= n + 1; ++i) {
flow[1][i] = 1;
cost[1][i] = 0;
for (int j = n + 2; j < 2 * n + 2; j++) {
f >> cost[i][j];
cost[j][i] = -cost[i][j];
flow[i][j] = 1;
}
}
while (dijkstra ()) {
int p = D;
while (p != 1){
c[t[p]][p] += 1;
c[p][t[p]] -= 1;
p = t[p];
}
}
for (int i = 1; i <= D; ++i) {
for (int j = i + 1; j < D; ++j) {
if (c[i][j]) {
tcost += cost[i][j];
}
}
}
g << tcost;
return 0;
}
bool dijkstra () {
for (int i = 2; i <= D; i++)
dmin[i] = t[i] = INF;
priority_queue <a> q;
t[1] = -1;
q.push({0, 1, -1});
while (!q.empty()) {
int node = q.top().node, cst = q.top().cst, tata = q.top().tata;
q.pop();
if (cst > dmin[node])
continue;
t[node] = tata;
if (node == D)
return 1;
for (int i = 1; i <= D; i++) {
if (flow[node][i] - c[node][i] > 0 && cost[node][i] + cst < dmin[i]) {
q.push({cost[node][i] + cst, i, node});
dmin[i] = cost[node][i] + cst;
}
}
}
return 0;
}