Powers of permutations
Given a natural number n, a permutation of \{0, 1,\dots,n−1\} is a sequence where each of the numbers 0, 1, …, n−1 occurs exactly once. For example, if n = 3, the sequences (1 2 0), (2 0 1) and (0 1 2) are permutations of \{0, 1, 2\}.
Given two permutations \sigma = (\sigma_0, \dots, \sigma_{n−1}) and \tau = (\tau_0, \dots, \tau_{n−1}) of \{0, 1, \dots,n−1\}, their product \sigma\circ\tau is defined as the permutation \rho = (\rho_0, \dots, \rho_{n−1}) such that \rho_i = \sigma_{\tau_i}. For example, if n = 3, \sigma = (1 2 0) and \tau = (2 0 1), then \sigma\circ\tau = (0 1 2), since:
- \tau_0 = 2 and \sigma_2 = 0,
- \tau_1 = 0 and \sigma_0 = 1, and
- \tau_2 = 1 and \sigma_1 = 2.
Make a program that, given a permutation \sigma and a natural k, computes the power of \sigma raised to k, that is \sigma^k = \underbrace{\sigma \circ\cdots\circ\sigma}_k. By convention, \sigma^0 = (0, 1, …, n−1).
Input: The input includes several cases. Each case consists in the number n (1 \leq n \leq 10^4), followed by n numbers between 1 and n that describe the permutation \sigma, followed by the number k (0 \leq k \leq 10^9).
Output: Write the permutation \sigma^k.
If needed, you can use that the product of permutations is associative.
The expected solution to this problem has cost O(n \log k).
Nothing really changes from the previous exercises. Just the meaning of the product.
// Powers of permutations
#include<iostream>
#include<vector>
using namespace std;
typedef vector<int> Permutation;
int n;//the length of the permutations
operator*(const Permutation& s, const Permutation& t){
Permutation (n);
Permutation cfor (int i = 0; i < s.size(); ++i)
[i] = s[t[i]];
creturn c;
}
(const Permutation& s, int k){
Permutation power(n);
Permutation outif (k==0){
for (int i = 0; i < n; ++i)
[i]=i;
outreturn out;
}
= power(s, k/2);
out return (k%2==0) ? out*out : s*out*out;
}
int main(){
while(cin >> n){
(n);
Permutation permfor(int i = 0; i < n; ++i)
>> perm[i];
cin int k;
>> k;
cin = power(perm,k);
Permutation pow for(int i = 0; i < n; ++i)
<< ((i==0) ? "" : " ") << pow[i];
cout << endl;
cout }
}