Cod sursa(job #23024)

Utilizator t30Rosu Teodor t30 Data 27 februarie 2007 22:24:45
Problema Critice Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.62 kb
#include<stdio.h>
#define NR 51000000
typedef struct nod { int x,c; nod *d; } nod;
typedef struct list { int x; list *d,*s; } list;
nod *v[1010],*a[1010];
list *l;

int n,m,h[1010],s[1010],f[1010][1010],c[1010][1010];;
long e[1010];

void add(int x,int y, int c)
{ nod *p;
  p=new nod;
  p->x=y;
  p->c=c;
  p->d=v[x];
  v[x]=p;
}


void READ()
{  int i,x,y,ca;

   FILE *f;
   f=fopen("critice.in","r");
   fscanf(f,"%d %d",&n,&m);
   for(i=1;i<=m;i++){
	fscanf(f,"%d %d %d",&x,&y,&ca);
	c[x][y]=c[y][x]=ca*NR+1;
	add(x,y,ca*NR+1);
	add(y,x,ca*NR+1);
   }
   fclose(f);
}

void INIT()
{ int i;
  for(i=1;i<=n;i++)
	h[i]=e[i]=s[i]=0;
  h[1]=n;

  nod *p;
  p=v[1];
  while(p){
	f[1][p->x]=p->c;
	f[p->x][1]=-p->c;
	e[p->x]=p->c;
	p=p->d;
  }


  list *P; l=NULL;
  for(i=2;i<n;i++){
     P=new list;
     P->x=i;
     P->d=l;
     P->s=0;
     if(l) l->s=P;
     l=P;
  }

  for(i=1;i<=n;i++)
     a[i]=v[i];

}

void RIDICA(int x)
{
  nod *p;
  p=v[x];
  int hh=5*n;
  while(p){
    if(h[p->x]>=h[x] && h[p->x]<hh) hh=h[p->x];
    p=p->d;
  }
  h[x]=hh+1;
}

void POMPEAZA(int x,int y)
{
   int min=(e[x]< c[x][y]-f[x][y]?e[x]:c[x][y]-f[x][y]);
   f[x][y]+=min;
   f[y][x]=-f[x][y];
   e[x]-=min;
   e[y]+=min;
}

void DESCARCA(int x)
{
   while(e[x]){
      if(!a[x]) {
		RIDICA(x); a[x]=v[x];    }

      else {
		if(c[x][ a[x]->x ]- f[x][ a[x]->x ]>0 && h[x]==h[ a[x]->x ]+1)
			POMPEAZA(x,a[x]->x);
		else a[x]=a[x]->d;
	   }

   }
}


void FLOW()
{  int x,hh;

   list *p=l;
    while(p){
	     x=p->x;
	     hh=h[x];
	     DESCARCA(x);
	     if(hh<h[x]) if(p->s){
			             p->s->d=p->d;
			             if(p->d) p->d->s=p->s;
			             p->s=0;
			             p->d=l;
			             l->s=p;
			             l=p;
		             }
	p=p->d;
   }
}
int abs(int x)
{  return (x<0?-x:x); }
    

void caut(int x,int k)
{
  int i,q;
  h[1]=x; s[x]=k;
  i=1; q=1;
  nod *p;
  while(i<=q){
     p=v[ h[i] ];
     while(p){
       if(c[ h[i] ][ p->x] -abs(f[ h[i] ][ p->x])>0 && s[p->x]==0)
	 { h[++q]=p->x;
	   s[p->x]=k;
	 }
     p=p->d;
     }
  i++;
  }

}

void SOLVE()
{
   FILE *f,*g;
   int i,x,y,cc;
   f=fopen("critice.in","r");
   g=fopen("critice.out","w");
   fscanf(f,"%d %d",&n,&m); 
   n=0;
   for(i=1;i<=m;i++){
     fscanf(f,"%d %d %d",&x,&y,&cc);
     if(s[x]*s[y]==-1) h[++n]=i;
   }
   fprintf(g,"%d\n",n);

   for(i=1;i<=n;i++)
      fprintf(g,"%d\n",h[i]);

   fclose(f);
   fclose(g);
}

int main()
{
READ();
INIT();
FLOW();

caut(1,1);
caut(n,-1);

SOLVE();

return 0;
}