Pagini recente » Cod sursa (job #2137978) | Cod sursa (job #1603725) | Cod sursa (job #811219) | Cod sursa (job #1096054) | Cod sursa (job #2466649)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
struct muchie{
int x, y;
bool cuplat = false;
}G[100005];
vector<int> A[20005];
stack<pair<int, int> > st; // stiva ce retine un nod si muchia folosita
int main()
{
int i, n, m, e, x, y, ln, lc, nurm, ct = 0;
unsigned int j;
bool sel[20005] = {0}, tempsel[20005] = {0};
fin >> n >> m >> e;
for(i = 1; i <= e; i++){
fin >> x >> y;
G[i].x = x; G[i].y = n + y;
A[x].push_back(i);
A[n + y].push_back(i);
}
for(i = 1; i <= n; i++){
for(j = 0; j < A[i].size(); j++){
if(!sel[G[A[i][j]].y]){ ct++;
sel[G[A[i][j]].y] = true;
G[A[i][j]].cuplat = true;
sel[i] = true;
break;
}
}
}
for(i = 1; i <= n; i++)
if(!sel[i]){
st.push(make_pair(i, 0));
tempsel[i] = true;
while(!st.empty()){
ln = st.top().first; lc = st.top().second;
if(ln <= n){
for(j = lc; j < A[ln].size(); j++){
if(G[A[ln][j]].cuplat == false){
nurm = G[A[ln][j]].y;
if(tempsel[nurm]) continue;
tempsel[nurm] = true;
st.pop();
st.push(make_pair(ln, j + 1));//updateaza muchia care a ramas de incercat
st.push(make_pair(nurm, 0));
break;
}
}
if(j == A[ln].size()) tempsel[st.top().first] = false, st.pop();
}
else{
for(j = lc; j < A[ln].size(); j++){
if(G[A[ln][j]].cuplat == true){
nurm = G[A[ln][j]].x;
if(tempsel[nurm]) continue;
tempsel[nurm] = true;
st.pop();
st.push(make_pair(ln, j + 1));
st.push(make_pair(nurm, 0));
break;
}
}
if(j == A[ln].size()) tempsel[st.top().first] = false, st.pop();
}
if(!st.empty() && !sel[st.top().first] && st.top().first != i) break;
}
if(!st.empty()){ ct++;
sel[st.top().first] = sel[i] = true;
tempsel[st.top().first] = false; st.pop();
while(!st.empty()){
x = st.top().first;
tempsel[x] = false;
j = st.top().second - 1;
G[A[x][j]].cuplat = 1 - G[A[x][j]].cuplat;
st.pop();
}
}
}
fout << ct << "\n";
for(i = 1; i <= e; i++)
if(G[i].cuplat) fout << G[i].x << " " << G[i].y - n << "\n";
return 0;
}