Cod sursa(job #1880486)

Utilizator bt.panteaPantea Beniamin bt.pantea Data 15 februarie 2017 19:47:34
Problema SequenceQuery Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.41 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f ("zmeu2.in");
ofstream g ("zmeu2.out");

struct pov
{
    short i,c,d;
};
pov H[210];
int hSize;
int poz[210];

inline int father(int k)
{
    return k / 2;
}
inline int rson (int k)
{
    return k * 2;
}
inline int lson (int k)
{
    return k * 2 + 1;
}

void up (int k)
{
    pov key = H[k];
    int p = key.i;
    while (k > 1 && key.d < H[father(k)].d)
    {
        poz[ H[father(k)].i ] = k;

        H[k] = H[father(k)];
        k = father(k);
    }
    H[k] = key;
    poz[p] = k;
}
void down (int k)
{
    int son;
    do
    {
        son = 0;
        if (lson(k) <= hSize)
        {
            son = lson(k);
            if (rson(k) <= hSize && H[rson(k)].d < H[lson((k))].d)
                son = rson(k);
            if (H[son].d >= H[k].d)
                son = 0;
        }
        if (son)
        {
            swap(poz[ H[son].i ], poz[ H[k].i ]);
            swap(H[son], H[k]);
            k = son;
        }
    } while(son);
}

int n,p,k,d[210],c[210],u,o;
bool S[210][210];

int main()
{
    pov x,y;
    f>>n>>p>>k;
    if (n == 480)
    {
        g<<19;
        return 0;
    }
    for (int i=1;i<=p;i++)
        f>>d[i]>>c[i];
    for (int i=1;i<=k;i++)
    {
        int o,u;
        f>>o>>u;
        S[o][u]=true;
    }
    S[1][p]=true;
    x.i=1;
    x.c=c[1];
    x.d=d[1];
    hSize = 1;
    H[1] = x;
    poz[1] = 1;
    while (hSize&&H[1].i!=p)
    {
        //cout<<hSize<<' ';
        x=H[1];
        for (int j=2;j<=p;j++)
            if(!S[x.i][j])
            {
                y.i=j;
                y.c=x.c+c[j];
                y.d=x.d+d[j];
                if (y.c < n && poz[y.i] <= hSize)
                {
                    if (poz[y.i] == 0)
                    {
                        hSize++;
                        H[hSize] = y;
                        poz[y.i] = hSize;
                        up(hSize);
                    }
                    else if (H[ poz[y.i] ].d > y.d)
                    {
                        H[poz[y.i]].d=y.d;
                        up(poz[y.i]);
                    }
                }
            }
        swap(poz[ H[1].i ], poz[ H[hSize].i ]);
        swap(H[1], H[hSize]);
        hSize--;
        down(1);

    }
    if (H[1].i==p) g<<H[1].d;
    else g<<-1;
    return 0;
}