Cod sursa(job #771411)

Utilizator igsifvevc avb igsi Data 25 iulie 2012 21:36:15
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator c Status done
Runda Arhiva educationala Marime 1.2 kb
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAXN 10000

struct list{
  short v;
  struct list *n;
} *G[MAXN];

short left[MAXN], right[MAXN], L, R, nr;
char used[MAXN];

int matching(int i)
{
  struct list *p;
  if(used[i]) return 0;
  used[i] = 1;

  for(p = G[i]; p; p = p->n)
    if(!right[p->v])
    {
      left[i] = p->v;
      right[p->v] = i;
      return 1;
    }
  for(p = G[i]; p; p = p->n)
    if(matching(right[p->v]))
    {
      left[i] = p->v;
      right[p->v] = i;
      return 1;
    }

  return 0;
}

int main()
{
  short i, a, b;
  struct list *p;
  FILE *in = fopen("cuplaj.in", "r");
  FILE *out = fopen("cuplaj.out", "w");
  
  fscanf(in, "%hd %hd %hd", &L, &R, &i);
  for(; i; --i)
  {
    fscanf(in, "%hd %hd", &a, &b);
    p = malloc(sizeof(struct list));
    p->v = b;
    p->n = G[a];
    G[a] = p;
  }
  
  for(i = 1; i <= L; ++i)
  {
    if( left[i] ) 
      continue; 
    else if( matching(i) ) 
      nr++;
    else
    {
      memset(used, 0, sizeof(used));
      if( matching(i) ) 
        nr++;
    }
  }

  fprintf(out, "%hd\n", nr);
  for(i = 1; i <= L; ++i)
    if( left[i] )
      fprintf(out, "%hd %hd\n", i, left[i]);

  fclose(in);
  fclose(out);
  return 0;
}