Cod sursa(job #56683)

Utilizator gigi_becaliGigi Becali gigi_becali Data 30 aprilie 2007 09:48:04
Problema Felinare Scor 8
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.6 kb
using namespace std;
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
#define maxn 9000
using namespace std;
vector<vector<int> > a;
bool viz[maxn];
int l[maxn], r[maxn];

int n, m;

void citire()
{
  int p, q;
  freopen("felinare.in", "r", stdin);
  scanf("%d %d\n", &n, &m);
  a.resize(n+1);
 

  while(m--)
    {
      scanf("%d %d\n", &p, &q);
      a[p].push_back(q);
    }
}

int pairup(int n)
{
  if(viz[n]) return 0;
  viz[n]=1;


  vector<int>::iterator i;

  for(i=a[n].begin();i!=a[n].end();++i)
    if(!l[*i] || pairup(l[*i]))
      {
	l[*i]=n;
	return 1;
      }
  return 0;
}

int pairup2(int n)
{
  if(viz[n]) return 0;
  int Q[maxn], p=1, q=1;
  Q[1]=n;
   viz[n]=1;
  int u;
  vector<int>::iterator i;

  while(p<=q)
    {

      u=Q[p++];
      //    if(viz[u])continue;//return 0;
      //viz[u]=1;
       //     printf("%d\n", u);
      for(i=a[u].begin();i!=a[u].end();++i)
   
	  if(!l[*i]  )
	    {
	      l[*i]=u;
	      //    viz[l[*i]]=1;
	      return 1;
	    }
	  else { if(!viz[l[*i]]) {Q[++q]=l[*i]; viz[l[*i]]=1;}}
    }
  return 0;
}

int main()
{
  time_t s; time(&s); srand(s%666013);
  citire();
  int flow=0;
  int random_order[maxn];
  for(int i=1;i<=n;i++) random_order[i]=i;
   random_shuffle(random_order+1, random_order+n+1);
   // for(int i=1;i<=n;i++) printf("%d ", random_order[i]); printf("\n");
 for(int i=1;i<=n;i++) 
   {
     //if(l[i])continue;

     if(pairup2(random_order[i])) ++flow;
     else {memset(viz, 0, sizeof(viz)); flow+=pairup2(random_order[i]);}
   }
 freopen("felinare.out", "w", stdout);
 printf("%d\n", n+n-flow);
 return 0;
}