Pagini recente » Cod sursa (job #678079) | Cod sursa (job #126545) | Rating Adrian (adryanos) | Cod sursa (job #2143589) | Cod sursa (job #2887049)
#include<bits/stdc++.h>
#define inf (1<<30)
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
int const N = 10001;
int n , m , e;
int st[N] , dr[N] , lv[N];///st[i] -> cuplajul din L al lui i
///L R
vector<int> v[N];
bool bfs(){
queue<int> q;
for(int i = 1 ; i <= n ; ++ i)
if(!dr[i])
q.push(i) , lv[i] = 0;
else
lv[i] = inf;///nod cuplat [i dr[y]]
lv[0] = inf;///nodurile necuplate sunt cuplate cu 0
while(!q.empty()){
auto x = q.front();
q.pop();
if(lv[x] < lv[0]){///daca il cuplez pe 0 cu cineva inseamna ca am gasit cuplaj din lant de lungime minimia, nu are rost sa caut mai adanc
for(auto y : v[x]){
///ma duc pe muchia [x , y] NECUPLATA
///verific daca y e cuplat
if(lv[st[y]] == inf){///y e cuplat cu st[y]
lv[st[y]] = 1 + lv[x];///[x , y] , [y , st[y]] , ...
q.push(st[y]);
}
}
}
}
return lv[0] != inf;///am gasit minim un lant alternant
}
bool dfs(int x){
if(x != 0){
for(auto y : v[x]){
if(lv[st[y]] == 1 + lv[x] && dfs(st[y])){
st[y] = x;
dr[x] = y;
return true;
}
}
lv[x] = inf;
return false;
}
return true;
}
int maxmatch(){
int r = 0;
fill(st , st + n + 1 , 0);
fill(dr , dr + m + 1 , 0);
while(bfs()){
for(int i = 1 ; i <= n ; ++ i)
if(!dr[i] && dfs(i))
++ r;
}
return r;
}
int main(){
fin >> n >> m >> e;
for(int i = 1 ; i <= e ; ++ i){
int x , y;
fin >> x >> y;
v[x].push_back(y);///L->R
}
fout << maxmatch() << '\n';
for(int i = 1 ; i <= n ; ++ i)
if(dr[i]) fout << i << ' ' << dr[i] << '\n';
return 0;
}