Pagini recente » Cod sursa (job #186646) | Cod sursa (job #927882) | Cod sursa (job #2538324) | Cod sursa (job #1391249) | Cod sursa (job #2615978)
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
#include <cmath>
#include <algorithm>
#define INF 1000000
using namespace std;
const int kNmax = 300;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
int n;
int m;
int sum = 0;
int C[kNmax][kNmax];
void read_input() {
ifstream fin("harta.in");
fin >> n;
int i, j, x, y;
memset(C, 0, sizeof(C));
for (i = 1; i <= n; ++i) {
fin >> x >> y;
sum += x;
C[0][i] = x;
C[n + i][(n << 1) + 1] = y;
}
for (i = 1; i <= n; ++i) {
for (j = 1; j <= n; ++j) {
if (i != j) {
C[i][n + j] = 1;
C[n + i][j] = 0;
}
}
}
fin.close();
}
bool bfs(queue<int>& nodes, queue<int>& flows, vector<int>& parents, vector<pair<int, int>>& result) {
int node = nodes.front(), flow = flows.front();
if (node == (n << 1) + 1) {
do {
if (C[parents[node]][node] < 0) {
C[parents[node]][node] += flow;
C[node][parents[node]] -= flow;
} else {
C[parents[node]][node] -= flow;
C[node][parents[node]] += flow;
}
node = parents[node];
} while (node);
return true;
}
nodes.pop();
flows.pop();
int i;
for (i = 0; i <= (n << 1) + 1; ++i) {
if (parents[i] == -1 && C[node][i]) {
parents[i] = node;
nodes.push(i);
flows.push(min(flow, abs(C[node][i])));
}
}
if (nodes.empty()) {
return false;
}
return bfs(nodes, flows, parents, result);
}
vector<pair<int, int>> get_result() {
int flow = 0;
vector<pair<int, int>> result;
while (1) {
queue<int> nodes;
queue<int> flows;
vector<int> parents((n << 1) + 2, -1);
parents[0] = 0;
nodes.push(0);
flows.push(INF);
if (!bfs(nodes, flows, parents, result)) {
break;
}
flow += flows.front();
}
int i, j;
for (i = 1; i <= n; ++i) {
for (j = 1; j <= n; ++j) {
if (i != j && !C[i][n + j]) {
result.emplace_back(make_pair(i, j));
}
}
}
return result;
}
void print_output(vector<pair<int, int>> result) {
ofstream fout("harta.out");
fout << sum << endl;
for (auto it = result.begin(); it != result.end(); ++it) {
fout << it->first << " " << it->second << endl;
}
fout.close();
}
};
int main() {
Task *task = new Task();
task->solve();
delete task;
return 0;
}