Cod sursa(job #284742)

Utilizator VmanDuta Vlad Vman Data 21 martie 2009 22:32:19
Problema Pitici Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.37 kb
using namespace std;
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <algorithm>

#define Nmax 1024
#define Kmax 1024

int N, M, K;
vector< pair<int, int> > G[Nmax];

int gin[Nmax], Q[Nmax], st, dr;
int H[Kmax], nrH;
int C[Nmax][Kmax], nr[Nmax];

void citire()
{
 int i, a, b, c;
 
 freopen("pitici.in","r",stdin);
 scanf("%d %d %d",&N, &M, &K);
 for (i=1; i<=M; ++i)
     {
      scanf("%d %d %d", &a, &b, &c);
      G[a].push_back( make_pair(b,c) );
      ++gin[b];
     }
}

void get_order()
{
 int nod;
 vector< pair<int,int> >::iterator it;
 
 Q[st=dr=0] = 1;
 while (st<=dr)
       {
        nod = Q[st];
        for (it=G[nod].begin(); it<G[nod].end(); ++it)
            {
             --gin[(*it).first];
             if ( !gin[(*it).first] ) Q[++dr] = (*it).first;
            }
        ++st;
       }
}

void add_heap(int V)
{
 int f, f2, t, aux;
 
 if (nrH == K && H[1] <= V) return;
 
 if (nrH < K)
    {
     H[++nrH] = V;
     f = nrH; t = f >> 1;
     while (t)
            if (H[f] > H[t]) { aux=H[t]; H[t]=H[f]; H[f]=aux; f=t; t=t>>1; }
               else break;     
     t=f;
    }
    else H[t=1] = V;

       while ((t<<1) <= nrH)
             {
              f=t<<1;
              if (f<nrH) f2=f+1;
                 else f2=f;
              if (H[f]>H[f2])
                 if (H[f]>H[t])
                    { aux=H[f]; H[f]=H[t]; H[t]=aux; t=f; }
                 else return;
              else if (H[f2]>H[t])
                   { aux=H[f2]; H[f2]=H[t]; H[t]=aux; t=f2; }
                   else return;
             }       
}

void solve()
{
 int nod, next, i;
 vector< pair<int,int> >::iterator it;
 
 nr[N] = 1;
 while (dr)
       {
        nod = Q[--dr];
        nrH = 0;
        for (it=G[nod].begin(); it<G[nod].end(); ++it)
            {
             next = (*it).first;
             for (i=1; i<=nr[next]; ++i)
                 add_heap(C[next][i] + (*it).second);
            }
        for (i=1; i<=nrH; ++i)
            C[nod][i] = H[i];
        if (nod==N) nr[nod] = 1;
           else nr[nod] = nrH;
       }
}

int main()
{
 int i;
 
 citire();
 
 get_order();
 
 solve();
 
 freopen("pitici.out","w",stdout);
 sort(C[1]+1, C[1]+K+1);
 for (i=1; i<=K; ++i)
     printf("%d ",C[1][i]);
 printf("\n");
 fclose(stdout); 

 return 0;
}