Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d5a6395

Browse files
authored
Binary Exp example (#842)
Provided coded example of Binary Exp on a permutation
1 parent 6076c29 commit d5a6395

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/algebra/binary-exp.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,27 @@ Therefore, we can raise this transformation matrix to the $n$-th power to find $
127127
128128
**Solution:** Simply raise the permutation to $k$-th power using binary exponentiation, and then apply it to the sequence. This will give you a time complexity of $O(n \log k)$.
129129
130+
```cpp
131+
vector<int> applyPermutation(vector<int> sequence, vector<int> permutation) {
132+
vector<int> newSequence(sequence.size());
133+
for(int i = 0; i < sequence.size(); i++) {
134+
newSequence[permutation[i]] = sequence[i];
135+
}
136+
return newSequence;
137+
}
138+
139+
vector<int> permute(vector<int> sequence, vector<int> permutation, long long b) {
140+
while (b > 0) {
141+
if (b & 1) {
142+
sequence = applyPermutation(sequence, permutation);
143+
}
144+
permutation = applyPermutation(permutation, permutation);
145+
b >>= 1;
146+
}
147+
return sequence;
148+
}
149+
```
150+
130151
**Note:** This task can be solved more efficiently in linear time by building the permutation graph and considering each cycle independently. You could then compute $k$ modulo the size of the cycle and find the final position for each number which is part of this cycle.
131152

132153
### Fast application of a set of geometric operations to a set of points

0 commit comments

Comments
 (0)