Cod sursa(job #1513928)

Utilizator hrazvanHarsan Razvan hrazvan Data 30 octombrie 2015 11:47:11
Problema Cuplaj maxim in graf bipartit Scor 70
Compilator c Status done
Runda Arhiva educationala Marime 1.88 kb
//lanturi alternante
#include <stdio.h>
#define MAXN 10000
#define MAXM 100000
#define INF 2000000000
int ult[2 * MAXN], next[2 * MAXM], nod[2 * MAXM];
int pairst[MAXN], pairdr[MAXN];
char tr[2 * MAXN];
int n, k;

int caut(int dist, int x){
  if(tr[x])
    return 0;
  tr[x] = 1;
  if(dist & 1)
    return caut(dist + 1, pairdr[x - n]);
  else{
    int poz;
    poz = ult[x];
    while(poz != -1){
      if(pairdr[nod[poz] - n] == -1){
        pairdr[nod[poz] - n] = x;
        pairst[x] = nod[poz] - n;
        return 1;
      }
      poz = next[poz];
    }
    poz = ult[x];
    while(poz != -1){
      if(caut(dist + 1, nod[poz])){
        pairdr[nod[poz] - n] = x;
        pairst[x] = nod[poz] - n;
        return 1;
      }
      poz = next[poz];
    }
  }
  return 0;
}

void del(int x){
  tr[x] = 0;
  int poz;
  poz = ult[x];
  while(poz != -1){
    if(tr[nod[poz]])
      del(nod[poz]);
    poz = next[poz];
  }
}

int main(){
  FILE *in = fopen("cuplaj.in", "r");
  int m, i, x, y, dr = 0;
  fscanf(in, "%d%d%d", &n, &k, &m);
  for(i = 0; i < n; i++)
    pairst[i] = -1;
  for(i = 0; i < k; i++)
    pairdr[i] = -1;
  for(i = 0; i < n + k; i++)
    ult[i] = -1;
  for(i = 0; i < m; i++){
    fscanf(in, "%d%d", &x, &y);
    x--;  y--;
    y += n;
    nod[dr] = x;
    next[dr] = ult[y];
    ult[y] = dr;
    dr++;
    nod[dr] = y;
    next[dr] = ult[x];
    ult[x] = dr;
    dr++;
  }
  fclose(in);
  char aux = 1;
  while(aux){
    aux = 0;
    for(i = 0; i < n; i++){
      if(pairst[i] == -1 && caut(0, i))
        aux = 1;
    }
    del(i);
  }
  FILE *out = fopen("cuplaj.out", "w");
  int nr = 0;
  for(i = 0; i < n; i++)
    if(pairst[i] != -1)
      nr++;
  fprintf(out, "%d\n", nr);
  for(i = 0; i < n; i++)
    if(pairst[i] != -1)
      fprintf(out, "%d %d\n", i + 1, pairst[i] + 1);
  fclose(out);
  return 0;
}