Cod sursa(job #730704)

Utilizator mihai995mihai995 mihai995 Data 6 aprilie 2012 19:24:00
Problema Atac Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.97 kb
#include <fstream>
#include <vector>
using namespace std;

const int N=32005,LG=16,inf=1<<30;
int T[LG][N],C[LG][N],rez[N],depth[N],n,m,k,A,B,c,D;
vector<int> a[N];

ifstream in("atac.in");
ofstream out("atac.out");

inline void next(int &x,int &y,int z)
{
    x=(A*x+B*y)%n+1;
    y=(c*y+D*z)%n+1;
}

int tata(int x,int L)
{
    for (int i=LG-1;i>=0;i--)
        if ((1<<i)<=L)
        {
            x=T[i][x];
            L-=1<<x;
        }
    return x;
}

int cost(int x,int L)
{
    int rez=inf;
    for (int i=LG;i>=0;i--)
        if ((1<<i)<=L)
        {
            rez=min(rez,C[i][x]);
            x=T[i][x];
            L-=1<<x;
        }
    return rez;
}

int lca(int x,int y)
{
    if (depth[x]<depth[y])
        y=tata(y,depth[y]-depth[x]);
    if (depth[x]>depth[y])
        x=tata(x,depth[x]-depth[y]);
    int L=depth[x];
    for (int i=LG-1;i>=0;i--)
        if ((1<<i)<=L && T[i][x]==T[i][y])
        {
            x=T[i][x];
            y=T[i][y];
            L-=(1<<i);
        }
    return L;
}

void dfs(int x,int L)
{
    depth[x]=L;
    for (vector<int>::iterator i=a[x].begin();i!=a[x].end();i++)
        dfs(*i,L+1);
}

int main()
{
    int x,y,L;
    in>>n>>m>>k;
    for (x=2;x<=n;x++)
    {
        in>>T[0][x]>>C[0][x];
        a[T[0][x]].push_back(x);
    }
    in>>x>>y>>A>>B>>c>>D;
    A%=n;B%=n;c%=n;D%=n;

    dfs(1,0);
    for (int i=1;i<LG;i++)
        for (int j=1;j<=n;j++)
        {
            T[i][j]=T[i-1][T[i-1][j]];
            if (!T[i][j])
                C[i][j]=inf;
            else
                C[i][j]=min(C[i-1][j],C[i-1][T[i-1][j]]);
        }

    for (int i=1;i<=m;i++)
    {
        if (x==y)
        {
            next(x,y,rez[i]);
            continue;
        }
        L=lca(x,y);
        rez[i]=min(cost(x,depth[x]-L),cost(y,depth[y]-L));
        next(x,y,rez[i]);
    }
    for (int i=m-k+1;i<=m;i++)
        out<<rez[i]<<"\n";
    return 0;
}