Cod sursa(job #130005)

Utilizator razvan2006razvan brezulianu razvan2006 Data 30 ianuarie 2008 20:35:30
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.68 kb
#include <iostream>   
#include <fstream>   
  
using namespace std;   
  
int N(0),   
    M(0),   
    prev[250001],   
    P(0),   
    Q(0),   
    A[19][250001];   
  
int p2[19] = {   
    1,   
    1<<1,   
    1<<2,   
    1<<3,   
    1<<4,   
    1<<5,   
    1<<6,   
    1<<7,   
    1<<8,   
    1<<9,   
    1<<10,   
    1<<11,   
    1<<12,   
    1<<13,   
    1<<14,   
    1<<15,   
    1<<16,   
    1<<17,   
    1<<18   
};   
  
int main(int argc, char *argv[]) {   
    ifstream fin("stramosi.in");   
    fin >> N >> M;   
    for (int i(1); i <= N; ++i) {   
        fin >> prev[i];   
        A[0][i] = prev[i];   
    }   
  
    for (int k(1); k < 19; ++k)    
        for (int i(1); i <= N; ++i)   
            A[k][i] = A[k - 1][A[k - 1][i]];   
  
    /*for (int i(0); i < 19; ++i) {  
        for (int j(1); j <= N; ++j)  
            cout << A[i][j] << "  ";  
        cout << endl;  
    }*/  
  
    ofstream fout("stramosi.out");   
    while (M--) {   
        fin >> Q >> P;   
        //cout << "Start: " << Q << " " << P  << endl;   
        while (P && Q) {   
            int i = 0;   
            while (p2[i] <= P)   
                ++i;   
            if (p2[i] > P)   
                --i;   
            Q = A[i][Q];   
            P -= p2[i];   
            //cout << "---    " << Q << " " << P << endl;   
        }   
        //cout << "Stop:  " << Q << " " << P << endl << endl;   
        fout << Q << endl;   
    }   
    fout.close();   
    fin.close();   
  
    return 0;   
}  
#include <iostream>
#include <fstream>

using namespace std;

int N(0),
	M(0),
	prev[250001],
	P(0),
	Q(0),
	A[19][250001];

int p2[19] = {
	1,
	1<<1,
	1<<2,
	1<<3,
	1<<4,
	1<<5,
	1<<6,
	1<<7,
	1<<8,
	1<<9,
	1<<10,
	1<<11,
	1<<12,
	1<<13,
	1<<14,
	1<<15,
	1<<16,
	1<<17,
	1<<18
};

int main(int argc, char *argv[]) {
	ifstream fin("stramosi.in");
	fin >> N >> M;
	for (int i(1); i <= N; ++i) {
		fin >> prev[i];
		A[0][i] = prev[i];
	}

	for (int k(1); k < 19; ++k) 
		for (int i(1); i <= N; ++i)
			A[k][i] = A[k - 1][A[k - 1][i]];

	/*for (int i(0); i < 19; ++i) {
		for (int j(1); j <= N; ++j)
			cout << A[i][j] << "  ";
		cout << endl;
	}*/

	ofstream fout("stramosi.out");
	while (M--) {
		fin >> Q >> P;
		//cout << "Start: " << Q << " " << P  << endl;
		while (P && Q) {
			int i = 0;
			while (p2[i] <= P)
				++i;
			if (p2[i] > P)
				--i;
			Q = A[i][Q];
			P -= p2[i];
			//cout << "---    " << Q << " " << P << endl;
		}
		//cout << "Stop:  " << Q << " " << P << endl << endl;
		fout << Q << endl;
	}
	fout.close();
	fin.close();

	return 0;
}