Playoff Restoration solution codeforces – 2k2k teams participate in a playoff tournament. The tournament consists of 2k−12k−1 games

2k2k teams participate in a playoff tournament. The tournament consists of 2k12k−1 games. They are held as follows: first of all, the teams are split into pairs: team 11 plays against team 22, team 33 plays against team 44 (exactly in this order), and so on (so, 2k12k−1 games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2k12k−1 teams remain. If only one team remains, it is declared the champion; otherwise, 2k22k−2 games are played: in the first one of them, the winner of the game “11 vs 22” plays against the winner of the game “33 vs 44“, then the winner of the game “55 vs 66” plays against the winner of the game “77 vs 88“, and so on. This process repeats until only one team remains.

After the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular:

  • the winner of the tournament gets place 11;
  • the team eliminated in the finals gets place 22;
  • both teams eliminated in the semifinals get place 33;
  • all teams eliminated in the quarterfinals get place 55;
  • all teams eliminated in the 1/8 finals get place 99, and so on.

For example, this picture describes one of the possible ways the tournament can go with k=3k=3, and the resulting places of the teams:

Playoff Restoration solution codeforces
After a tournament which was conducted by the aforementioned rules ended, its results were encoded in the following way. Let pipi be the place of the ii-th team in the tournament. The hash value of the tournament hh is calculated as h=(i=12kiApi)mod998244353h=(∑i=12ki⋅Api)mod998244353, where AA is some given integer.

Unfortunately, due to a system crash, almost all tournament-related data was lost. The only pieces of data that remain are the values of kkAA and hh. You are asked to restore the resulting placing of the teams in the tournament, if it is possible at all.

Input

The only line contains three integers kkAA and hh (1k51≤k≤5100A108100≤A≤1080h9982443520≤h≤998244352).

Output

If it is impossible to find any placing of the teams that is consistent with the data you have, print one integer 1−1.

Otherwise, print 2k2k integers, where ii-th integer should be equal to pipi (the place of the ii-th team). Note that your answer should be consistent with one of the possible ways the tournament could go, and note that the initial structure of the tournament is fixed (for example, teams 11 and 22 always play in the first phase of the tournament against each other). If there are multiple ways to restore the places of the teams which are consistent with the data you have, print any of them.

Examples

input

Copy
3 1337 75275197

output

Copy
5 3 5 2 1 5 5 3 

input

Copy
2 100 5040100

output

Copy
1 3 3 2 

input

Copy
2 100 7020100

output

Copy
-1
Note

The tournament for the first example is described in the statement.

For the third example, the placing [1,2,3,3][1,2,3,3] (team 11 gets place 11, team 22 gets place 22, teams 33 and 44 get place 33) could result in a hash value of 70201007020100 with A=100A=100, but no tournament can result in such placing since teams 11 and 22 play against each other in the semifinals, so they cannot get two first places.

Table of Contents

Java

import java.io.*;
import java.util.*;

public class CF1569E extends PrintWriter {
CF1569E() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1569E o = new CF1569E(); o.main(); o.flush();
}

static final int MD = 998244353;
int[] places = { 1, 2, 3, 5, 9, 17 };
int[] qu, pp;
int k, n;
int solve(int b) {
int cnt = 0;
for (int i = 0; i < n / 2; i++)
qu[cnt++] = i;
for (int l = k; l >= 2; l--) {
int p = places[l];
int cnt_ = 0;
for (int h = 0; h < cnt; h += 2) {
int i = qu[h], j = qu[h + 1];
if ((b & 1) == 0) {
pp[i] = p;
qu[cnt_++] = j;
} else {
pp[j] = p;
qu[cnt_++] = i;
}
b >>= 1;
}
cnt = cnt_;
}
int i_ = qu[0];
pp[i_] = 0;
return i_;
}
void report(int a, int b, boolean left) {
for (int z = 1; z <= 2; z++) {
int i_ = solve(z == 1 ? a : b);
pp[i_] = left ? z : 3 ^ z;
for (int i = 0; i < n / 2; i++)
print(pp[i] + " ");
}
println();
}
void main() {
k = sc.nextInt();
n = 1 << k;
int x = sc.nextInt();
int s = sc.nextInt();
int[] powers = new int[18];
for (int p = 1, h = 0; h <= 17; h++) {
powers[h] = p;
p = (int) ((long) p * x % MD);
}
int m = n / 2 - 1;
int[] l1 = new int[1 << m];
int[] l2 = new int[1 << m];
int[] r1 = new int[1 << m];
int[] r2 = new int[1 << m];
qu = new int[n / 2];
pp = new int[n / 2];
for (int b = 0; b < 1 << m; b++) {
int i_ = solve(b);
long sl = 0, sr = 0;
for (int i = 0; i < n / 2; i++)
if (i != i_) {
sl = (sl + (long) (i + 1) * powers[pp[i]]) % MD;
sr = (sr + (long) (n / 2 + i + 1) * powers[pp[i]]) % MD;
}
l1[b] = (int) ((sl + (long) (i_ + 1) * powers[1]) % MD);
l2[b] = (int) ((sl + (long) (i_ + 1) * powers[2]) % MD);
r1[b] = (int) ((sr + (long) (n / 2 + i_ + 1) * powers[1]) % MD);
r2[b] = (int) ((sr + (long) (n / 2 + i_ + 1) * powers[2]) % MD);
}
HashMap<Integer, Integer> mp1 = new HashMap<>();
HashMap<Integer, Integer> mp2 = new HashMap<>();
for (int a = 0; a < 1 << m; a++) {
mp1.put(l1[a], a);
mp2.put(l2[a], a);
}
for (int b = 0; b < 1 << m; b++) {
Integer a;
a = mp1.get(s - r2[b]);
if (a != null) {
report(a, b, true);
return;
}
a = mp1.get(MD + s - r2[b]);
if (a != null) {
report(a, b, true);
return;
}
a = mp2.get(s - r1[b]);
if (a != null) {
report(a, b, false);
return;
}
a = mp2.get(MD + s - r1[b]);
if (a != null) {
report(a, b, false);
return;
}
}
println(-1);
}
}

Pyhton

import sys
input = sys.stdin.readline

k,A,h=map(int,input().split())
team=1<<k
mod=998244353

POW=[1]
for i in range(100):
POW.append(POW[-1]*A%mod)

ANS=[(1<<(k-1))+1]*(team//2)
X=tuple([i for i in range(team//2)])

ALLLIST=[]

def half_all(ANS,X,Y,i):
#print(ANS,X,Y,i)
if i==0:
#print("!",ANS)
ALLLIST.append(tuple(ANS))
return ANS

if X==tuple():
X=Y
Y=tuple()
half_all(ANS,X,Y,i-1)
return

X=list(X)
ANS=list(ANS)

p=X.pop()
q=X.pop()

ANS[p]=ANS[p]//2+1

half_all(tuple(ANS),tuple(X),Y+(p,),i)

ANS[p]=ANS[p]*2-1

ANS[q]=ANS[q]//2+1

half_all(tuple(ANS),tuple(X),Y+(q,),i)

half_all(ANS,X,tuple(),k-1)

SCORE01=[0]*len(ALLLIST)
SCORE02=[0]*len(ALLLIST)
SCORE11=[0]*len(ALLLIST)
SCORE12=[0]*len(ALLLIST)

for i in range(len(ALLLIST)):
LIST=ALLLIST[i]

sc01=sc02=sc11=sc12=0

#print(LIST)

for j in range(team//2):
#print(sc01,sc02,sc11,sc12)
if LIST[j]!=2:
sc01+=(j+1)*POW[LIST[j]]%mod
sc02+=(j+1)*POW[LIST[j]]%mod
sc01%=mod
sc02%=mod

sc11+=(j+1+team//2)*POW[LIST[j]]%mod
sc12+=(j+1+team//2)*POW[LIST[j]]%mod
sc11%=mod
sc12%=mod
else:
sc01+=(j+1)*POW[1]%mod
sc02+=(j+1)*POW[2]%mod
sc01%=mod
sc02%=mod

sc11+=(j+1+team//2)*POW[1]%mod
sc12+=(j+1+team//2)*POW[2]%mod
sc11%=mod
sc12%=mod
#print(sc01,sc02,sc11,sc12)

SCORE01[i]=sc01
SCORE02[i]=sc02
SCORE11[i]=sc11
SCORE12[i]=sc12


SCSET11=set(SCORE11)
SCSET12=set(SCORE12)

for i in range(len(ALLLIST)):
if (h-SCORE01[i])%mod in SCSET12:
k=SCORE12.index((h-SCORE01[i])%mod)

#print(i,k)
LANS=list(ALLLIST[i]+ALLLIST[k])

for j in range(len(LANS)):
if LANS[j]==2:
LANS[j]=1
break
print(*LANS)
break

if (h-SCORE02[i])%mod in SCSET11:
k=SCORE11.index((h-SCORE02[i])%mod)

#print(i,k)
LANS=list(ALLLIST[i]+ALLLIST[k])

for j in range(len(LANS)-1,-1,-1):
if LANS[j]==2:
LANS[j]=1
break
print(*LANS)
break

else:
print(-1)


 

 

C++ 

#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
const int C=64;
const int mod=998244353;
int k,a,h;
int pw[C];
map <int,int> tg[2];
int v[10][C],rk[C];
int p[C];
int cal(int s,int o)
{
for (int i=0;i<(1<<k-1);i++)
v[k-1][i]=i+o+1;
for (int i=k-1;i>0;i--)
for (int j=0;j<(1<<i);j+=2)
{
if (s&1)
{
v[i-1][j>>1]=v[i][j+1];
rk[v[i][j]]=p[i];
}
else
{
v[i-1][j>>1]=v[i][j];
rk[v[i][j+1]]=p[i];
}
s>>=1;
}
if (s&1)
rk[v[0][0]]=2;
else
rk[v[0][0]]=1;
int ret=0;
for (int i=0;i<(1<<k-1);i++)
{
int cur=i+o+1;
ret=(ret+1ll*cur*pw[rk[cur]])%mod;
}
return ret;
}
int main()
{
p[1]=3;
p[2]=5;
p[3]=9;
p[4]=17;
scanf("%d%d%d",&k,&a,&h);
pw[0]=1;
for (int i=1;i<=(1<<k);i++)
pw[i]=1ll*pw[i-1]*a%mod;
for (int i=0;i<(1<<(1<<k-1));i++)
{
int v=cal(i,0);
int hb=i>>((1<<k-1)-1);
tg[hb][v]=i+1;
}
for (int i=0;i<(1<<(1<<k-1));i++)
{
int v=cal(i,1<<(k-1));
int hb=i>>((1<<k-1)-1);
if (tg[hb^1][(mod+h-v)%mod])
{
int j=tg[hb^1][(mod+h-v)%mod]-1;
cal(j,0);
cal(i,1<<(k-1));
for (int i=1;i<=(1<<k);i++)
printf("%d%c",rk[i]," \n"[i==(1<<k)]);
return 0;
}
}
printf("-1\n");
return 0;
}

Rust

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
($($r:tt)*) => {
let stdin = std::io::stdin();
let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
let mut next = move || -> String{
bytes.by_ref().map(|r|r.unwrap() as char)
.skip_while(|c|c.is_whitespace())
.take_while(|c|!c.is_whitespace())
.collect()
};
input_inner!{next, $($r)*}
};
}

macro_rules! input_inner {
($next:expr) => {};
($next:expr,) => {};
($next:expr, $var:ident : $t:tt $($r:tt)*) => {
let $var = read_value!($next, $t);
input_inner!{$next $($r)*}
};
}

macro_rules! read_value {
($next:expr, ( $($t:tt),* )) => { ($(read_value!($next, $t)),*) };
($next:expr, [ $t:tt ; $len:expr ]) => {
(0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
};
($next:expr, chars) => {
read_value!($next, String).chars().collect::<Vec<char>>()
};
($next:expr, usize1) => (read_value!($next, usize) - 1);
($next:expr, [ $t:tt ]) => {{
let len = read_value!($next, usize);
read_value!($next, [$t; len])
}};
($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

/// Verified by https://atcoder.jp/contests/abc198/submissions/21774342
mod mod_int {
use std::ops::*;
pub trait Mod: Copy { fn m() -> i64; }
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ModInt<M> { pub x: i64, phantom: ::std::marker::PhantomData<M> }
impl<M: Mod> ModInt<M> {
// x >= 0
pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }
fn new_internal(x: i64) -> Self {
ModInt { x: x, phantom: ::std::marker::PhantomData }
}
pub fn pow(self, mut e: i64) -> Self {
debug_assert!(e >= 0);
let mut sum = ModInt::new_internal(1);
let mut cur = self;
while e > 0 {
if e % 2 != 0 { sum *= cur; }
cur *= cur;
e /= 2;
}
sum
}
#[allow(dead_code)]
pub fn inv(self) -> Self { self.pow(M::m() - 2) }
}
impl<M: Mod, T: Into<ModInt<M>>> Add<T> for ModInt<M> {
type Output = Self;
fn add(self, other: T) -> Self {
let other = other.into();
let mut sum = self.x + other.x;
if sum >= M::m() { sum -= M::m(); }
ModInt::new_internal(sum)
}
}
impl<M: Mod, T: Into<ModInt<M>>> Sub<T> for ModInt<M> {
type Output = Self;
fn sub(self, other: T) -> Self {
let other = other.into();
let mut sum = self.x - other.x;
if sum < 0 { sum += M::m(); }
ModInt::new_internal(sum)
}
}
impl<M: Mod, T: Into<ModInt<M>>> Mul<T> for ModInt<M> {
type Output = Self;
fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }
}
impl<M: Mod, T: Into<ModInt<M>>> AddAssign<T> for ModInt<M> {
fn add_assign(&mut self, other: T) { *self = *self + other; }
}
impl<M: Mod, T: Into<ModInt<M>>> SubAssign<T> for ModInt<M> {
fn sub_assign(&mut self, other: T) { *self = *self - other; }
}
impl<M: Mod, T: Into<ModInt<M>>> MulAssign<T> for ModInt<M> {
fn mul_assign(&mut self, other: T) { *self = *self * other; }
}
impl<M: Mod> Neg for ModInt<M> {
type Output = Self;
fn neg(self) -> Self { ModInt::new(0) - self }
}
impl<M> ::std::fmt::Display for ModInt<M> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.x.fmt(f)
}
}
impl<M: Mod> ::std::fmt::Debug for ModInt<M> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
let (mut a, mut b, _) = red(self.x, M::m());
if b < 0 {
a = -a;
b = -b;
}
write!(f, "{}/{}", a, b)
}
}
impl<M: Mod> From<i64> for ModInt<M> {
fn from(x: i64) -> Self { Self::new(x) }
}
// Finds the simplest fraction x/y congruent to r mod p.
// The return value (x, y, z) satisfies x = y * r + z * p.
fn red(r: i64, p: i64) -> (i64, i64, i64) {
if r.abs() <= 10000 {
return (r, 1, 0);
}
let mut nxt_r = p % r;
let mut q = p / r;
if 2 * nxt_r >= r {
nxt_r -= r;
q += 1;
}
if 2 * nxt_r <= -r {
nxt_r += r;
q -= 1;
}
let (x, z, y) = red(nxt_r, r);
(x, y - q * z, z)
}
} // mod mod_int

macro_rules! define_mod {
($struct_name: ident, $modulo: expr) => {
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct $struct_name {}
impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }
}
}
const MOD: i64 = 998_244_353;
define_mod!(P, MOD);
type MInt = mod_int::ModInt<P>;

trait Change { fn chmax(&mut self, x: Self); fn chmin(&mut self, x: Self); }
impl<T: PartialOrd> Change for T {
fn chmax(&mut self, x: T) { if *self < x { *self = x; } }
fn chmin(&mut self, x: T) { if *self > x { *self = x; } }
}

fn main() {
// In order to avoid potential stack overflow, spawn a new thread.
let stack_size = 104_857_600; // 100 MB
let thd = std::thread::Builder::new().stack_size(stack_size);
thd.spawn(|| solve()).unwrap().join().unwrap();
}

fn dfs(l: i64, r: i64, rnk: i64, a: MInt) -> Vec<(MInt, i64, Vec<i64>)> {
let nxtrnk = if rnk <= 2 { 3 } else { 2 * rnk - 1 };
if r - l == 1 {
let t = vec![if rnk <= 2 { rnk } else { 0 }];
return vec![(if rnk <= 2 { a.pow(t[0]) * l } else { 0.into() }, l, t)];
}
let mid = (r + l) / 2;
let fst = dfs(l, mid, nxtrnk, a);
let snd = dfs(mid, r, nxtrnk, a);
let mut ans = vec![];
let now = a.pow(nxtrnk);
let fin = if rnk <= 2 { a.pow(rnk) } else { MInt::new(0) };
for (v1, n1, t1) in fst {
for &(v2, n2, ref t2) in &snd {
let tmp = v1 + v2;
let mut t = t1.clone();
t.extend(t2);
t[(n2 - l) as usize] = nxtrnk;
if rnk <= 2 {
t[(n1 - l) as usize] = rnk;
}
ans.push((tmp + now * n2 + fin * n1, n1, t.clone()));
t[(n2 - l) as usize] = 0;
t[(n1 - l) as usize] = nxtrnk;
if rnk <= 2 {
t[(n2 - l) as usize] = rnk;
}
ans.push((tmp + now * n1 + fin * n2, n2, t));
}
}
ans
}

fn calc(a: &[(MInt, i64, Vec<i64>)], b: &[(MInt, i64, Vec<i64>)], h: MInt)
-> Option<Vec<i64>> {
let mut hm = HashMap::new();
for i in 0..a.len() {
hm.insert(a[i].0, i);
}
for &(b, _, ref t) in b {
let res = h - b;
if let Some(&idx) = hm.get(&res) {
let mut t1 = a[idx].2.clone();
t1.extend(t);
return Some(t1);
}
}
None
}

fn solve() {
let out = std::io::stdout();
let mut out = BufWriter::new(out.lock());
macro_rules! puts {($($format:tt)*) => (let _ = write!(out,$($format)*););}
#[allow(unused)]
macro_rules! putvec {
($v:expr) => {
for i in 0..$v.len() {
puts!("{}{}", $v[i], if i + 1 == $v.len() {"\n"} else {" "});
}
}
}
input!(k: usize, a: i64, h: i64);
let fst0 = dfs(1, (1 << (k - 1)) + 1, 1, a.into());
let fst1 = dfs(1, (1 << (k - 1)) + 1, 2, a.into());
let snd0 = dfs((1 << (k - 1)) + 1, (1 << k) + 1, 1, a.into());
let snd1 = dfs((1 << (k - 1)) + 1, (1 << k) + 1, 2, a.into());
// eprintln!("fst0 = {:?}, fst1 = {:?}", fst0, fst1);
let h = MInt::new(h);
if let Some(v) = calc(&fst0, &snd1, h) {
putvec!(v);
return;
}
if let Some(v) = calc(&fst1, &snd0, h) {
putvec!(v);
return;
}
puts!("-1\n");
}

Also read : Playoff Restoration solution codeforces

Leave a Reply

Your email address will not be published. Required fields are marked *

*