Pagini recente » Cod sursa (job #2125328) | Cod sursa (job #2290446) | Cod sursa (job #750256) | Cod sursa (job #1181132) | Cod sursa (job #1562117)
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int Mx = 300;
int n,last,sol;
int parent[Mx];
int flow[Mx][Mx],capacity[Mx][Mx];
bool visited[Mx];
vector< int > G[Mx];
deque< int > dq;
void add_edge(int a,int b,int c)
{
G[a].push_back(b);
G[b].push_back(a);
capacity[a][b] += c;
}
bool bfs()
{
dq.clear();
dq.push_back(0);
memset(visited,0,sizeof(visited));
visited[0] = 1;
while (!dq.empty())
{
int x = dq.front();
dq.pop_front();
if (x == last)
continue;
for (int i = 0;i < G[x].size();i++)
{
int y = G[x][i];
if (visited[y] || capacity[x][y] == flow[x][y])
continue;
visited[y] = 1;
dq.push_back(y);
parent[y] = x;
}
}
return visited[last];
}
int max_flow()
{
int sol = 0;
while (bfs())
{
for (int i = 0;i < G[last].size();i++)
{
int x = G[last][i],y = 1;
if (!visited[last] || capacity[x][last] == flow[x][last])
continue;
parent[last] = x;
for (x = last;x;x = parent[x])
y = min(y,capacity[parent[x]][x] - flow[parent[x]][x]);
if (!y)
continue;
for (x = last;x;x = parent[x])
{
flow[parent[x]][x] += y;
flow[x][parent[x]] -= y;
}
sol += y;
}
}
return sol;
}
int main()
{
freopen("harta.in","r",stdin);
freopen("harta.out","w",stdout);
scanf("%d",&n);
last = 2 * n + 1;
for (int i = 1;i <= n;i++)
{
int a,b;
scanf("%d %d",&a,&b);
sol += a;
add_edge(0,i,b);
add_edge(n + i,last,a);
}
for (int i = 1;i <= n;i++)
for (int j = 1;j <= n;j++)
if (i != j)
add_edge(i,n + j,1);
max_flow();
printf("%d\n",sol);
for (int i = 1;i <= n;i++)
for (int j = 1;j <= n;j++)
if (flow[i][n + j] == 1)
printf("%d %d\n",i,j);
return 0;
}