Pagini recente » Cod sursa (job #1971114) | Cod sursa (job #2170235) | Cod sursa (job #287530) | Cod sursa (job #1760408) | Cod sursa (job #2714552)
#include <bits/stdc++.h>
using namespace std;
ifstream f("cuplaj.in");
ofstream g("cuplaj.out");
//#define int long long
const int Max = 2e4 + 5;
void nos()
{
//ios_base::sync_with_stdio(false);
//f.tie(NULL);
// g.tie(NULL);
}
vector < int > v[Max];
int stanga,dreapta;
int muchii;
class sfantu_bulan{
public:
size_t operator () (const pair < int , int > &p) const
{
return p.first * (1e4 + 10) + p.second;
}
};
unordered_map < pair < int, int >, int , sfantu_bulan > cost;
int source = 0;
int destination = Max - 1;
void add_edge( int n1, int n2)
{
v[n1].push_back(n2);
v[n2].push_back(n1);
cost.insert(pair < pair < int, int >, int > ({n1,n2}, 1 ) );
cost.insert(pair < pair < int, int >, int > ({n2,n1}, 0 ) );
}
int max_flow;
unordered_set < int > path_close;
void read()
{
f>>stanga>>dreapta>>muchii;
int i;
for(i=1; i<=muchii; i++)
{
int n1,n2;
f>>n1>>n2;
n2 += 1e4 + 1;
add_edge(source,n1);
add_edge(n1,n2);
add_edge(n2,destination);
path_close.insert(n2);
}
}
int parent[Max];
unordered_set < pair < int, int > , sfantu_bulan > sol;
void relax(int leaf)
{
int path_flow = cost.find({leaf,destination}) -> second;
int nod;
for(int nod = leaf; nod!=source; nod = parent[nod])
{
int this_cost = cost.find({parent[nod],nod}) -> second;
path_flow = min(path_flow,this_cost);
}
if(path_flow!=1)
return;
cost.erase({leaf,destination});
// cost.find({destination,leaf}) -> second += path_flow;
for(int nod = leaf; nod!=source; nod = parent[nod])
{
cost.find({parent[nod],nod}) -> second -= path_flow;
cost.find({nod,parent[nod]}) -> second += path_flow;
int nod1 = parent[nod];
int nod2 = nod;
if(nod1 < nod2 and nod1 != source)
sol.insert({nod1,nod2});
if(nod1 > nod2 and nod1 != destination)
sol.erase({nod2,nod1});
}
max_flow += path_flow;
}
bool bfs()
{
bool relaxed[Max] = {};
bool viz[Max] = {};
queue < int > q;
q.push(source);
viz[source] = 1;
parent[source] = -1;
while(!q.empty())
{
int nod = q.front();
q.pop();
bool is_right = path_close.find(nod)!=path_close.end();
if(is_right and !relaxed[nod])
{
// daca e nod vecin cu destination
auto pointer_cost = cost.find({nod,destination});
if(pointer_cost!=cost.end() and pointer_cost -> second > 0)
{
relaxed[nod] = 1;
relax(nod);
}
}
for(auto vec : v[nod])
if(!viz[vec])
{
auto pointer_cost = cost.find({nod,vec});
if(pointer_cost!=cost.end() and pointer_cost -> second > 0)
{
q.push(vec);
parent[vec] = nod;
viz[vec] = 1;
}
}
}
return viz[destination];
}
void solve()
{
while(bfs());
g<<max_flow<<'\n';
for(auto it : sol)
g<<it.first<<' '<<it.second - 1e4 - 1<<'\n';
}
void restart()
{
}
int32_t main()
{
nos();
read();
solve();
restart();
return 0;
}