Pagini recente » Cod sursa (job #1045986) | Cod sursa (job #2186327) | Cod sursa (job #1845412) | Cod sursa (job #2911924) | Cod sursa (job #2894121)
// This program was written on 26.04.2022
// for problem cuplaj
// by Mircea Rebengiuc
// This program was reviewed on 27.04.2022
// by Tiberiu Musat
// All changes are highlighted and explained with a comment stating with [!]
#include <stdio.h>
#include <ctype.h>
#include <vector>
#define MAXN 20000
#define NIL -1
std::vector<int> adj[MAXN];
short pair[MAXN]; // [!] Use short to make the program more cache-friendly
bool viz[MAXN]; // [!] Use bool to make the program more cache-friendly
int stamp = 1;
bool match( int u ){
viz[u] = true;
// putem lega usor?
for( int v : adj[u] ){
if( pair[v] == NIL ){
// [!] Unmatching not necessary
//if( pair[u] != NIL )// decuplam daca avea o pereche inainte
// pair[pair[u]] = NIL;
pair[u] = v;
pair[v] = u;
return true;
}
}
for( int v : adj[u] )
if( viz[v] != true ){
viz[v] = true;
if( match( pair[v] ) ){// incercam sa gasim alta pereche pentru perecea lui v
// [!] Unmatching not necessary
//if( pair[u] != NIL )// decuplam daca avea o pereche inainte
// pair[pair[u]] = NIL;
pair[u] = v;
pair[v] = u;
return true;
}
}
return false;
}
FILE *fin, *fout;
static inline int fgetint(){
int n = 0, ch;
while( !isdigit( ch = fgetc( fin ) ) );
do
n = n * 10 + ch - '0';
while( isdigit( ch = fgetc( fin ) ) );
return n;
}
int main(){
fin = fopen( "cuplaj.in", "r" );
fout = fopen( "cuplaj.out", "w" );
int nl, nr, n, m, i, j, a, b, cuplaj;
nl = fgetint();
nr = fgetint();
n = nl + nr;
for( i = 0 ; i < n ; i++ )
pair[i] = NIL;
for( m = fgetint() ; m-- ; ){
a = fgetint() - 1;
b = fgetint() - 1 + nl;
adj[a].push_back( b );
adj[b].push_back( a );
}
for( i = 0 ; i < nl ; i++ ) { // [!] No need to try matching nodes on both sides. One side is enough
if (pair[i] == NIL) // [!] Don't match those already matched
match( i );
// [!] Same nodes can be visited again in a new DFS. Reset viz vector
for ( j = 0 ; j < n ; j++ )
viz[j] = false;
}
cuplaj = 0;
for( i = 0 ; i < nl ; i++ )
cuplaj += (pair[i] != NIL);
fprintf( fout, "%d\n", cuplaj );
for( i = 0 ; i < nl ; i++ )
if( pair[i] != NIL )
fprintf( fout, "%d %d\n", i + 1, pair[i] - nl + 1 );
fclose( fin );
fclose( fout );
return 0;
}