puwaer/puwaer_code_translation huggingface dataset:
AtCoder problem 058

C++ solution:
#include <vector>

#include <iostream>

using namespace std;

int digit_sum(int x) {

	int ans = 0;

	while (x > 0) {

		ans += x % 10;

		x /= 10;

	}

	return ans;

}

int main() {

	const int mod = 100000;

	int N; long long K;

	cin >> N >> K;

	vector<int> nxt(mod);

	for (int i = 0; i < mod; ++i) {

		nxt[i] = (i + digit_sum(i)) % mod;

	}

	vector<int> time_stamp(mod, -1);

	int pos = N, cnt = 0;

	while (time_stamp[pos] == -1) {

		time_stamp[pos] = cnt;

		pos = nxt[pos];

		++cnt;

	}

	int cycle = cnt - time_stamp[pos];

	if (K >= time_stamp[pos]) {

		K = (K - time_stamp[pos]) % cycle + time_stamp[pos];

	}

	int answer = -1;

	for (int i = 0; i < mod; ++i) {

		if (time_stamp[i] == K) {

			answer = i;

		}

	}

	cout << answer << endl;

	return 0;

}


Python solution: import sys
def input(): return sys.stdin.readline().strip()
def INTS():  return [ int(s) for s in input().split(" ")]
def log(*args, **kwargs): print("DEBUG:", *args, **kwargs, file=sys.stderr)

class Doubling():
    def __init__(self, n, k_max, f) -> None:
        """要素数nのダブリングテーブルを作成します。"""

        k_bits = k_max.bit_length()

        # dub[i][j] = 値jを2**i回操作した結果
        dub = [[0] * n for _ in range(k_bits)]

        # 1回(2**0回)操作した結果を作成
        for j in range(n):
            dub[0][j] = f(j)

        # 2**i回操作した結果を順に作成
        # 2**(i-1)回操作を2回すれば2**i回操作したことになる
        for i in range(1, k_bits):
            for j in range(n):
                dub[i][j] = dub[i - 1][dub[i - 1][j]]

        self.doubling_table = dub

    def get(self, x, k):
        """xをk回操作した値を取得します。"""
        # kをビットごとに分解して、2**a + 2**b + 2**c + ... の形で考える。
        # xを2**a回操作した結果を2**b回操作した結果を2**c回操作… のように順に適用する
        now = x
        for i in range(k.bit_length()):
            if k>>i & 1:
                now = self.doubling_table[i][now]

        return now

def f(n):
    """(n + nの桁ごとの和) mod 10万 を返します。"""
    s = 0
    x = n
    while x > 0:
        s += x % 10
        x //= 10

    return (n+s) % 100000

def main():
    n, k = INTS()
    dub = Doubling(100000, k, f)
    print(dub.get(n,k))
main()
AtCoder problem 058

C++ solution:
#include <vector>

#include <iostream>

using namespace std;

int digit_sum(int x) {

	int ans = 0;

	while (x > 0) {

		ans += x % 10;

		x /= 10;

	}

	return ans;

}

int main() {

	const int mod = 100000;

	int N; long long K;

	cin >> N >> K;

	vector<int> nxt(mod);

	for (int i = 0; i < mod; ++i) {

		nxt[i] = (i + digit_sum(i)) % mod;

	}

	vector<int> time_stamp(mod, -1);

	int pos = N, cnt = 0;

	while (time_stamp[pos] == -1) {

		time_stamp[pos] = cnt;

		pos = nxt[pos];

		++cnt;

	}

	int cycle = cnt - time_stamp[pos];

	if (K >= time_stamp[pos]) {

		K = (K - time_stamp[pos]) % cycle + time_stamp[pos];

	}

	int answer = -1;

	for (int i = 0; i < mod; ++i) {

		if (time_stamp[i] == K) {

			answer = i;

		}

	}

	cout << answer << endl;

	return 0;

}





Kuin solution: func main()
	var n: int :: cui@inputInt()
	var k: int :: cui@inputInt()
	
	var map: dict<int, int> :: #dict<int, int>
	for i(1, k)
		do n :: f(n)
		var prev: int :: map.get(n, &)
		if(prev <> 0)
			var len: int :: i - prev
			do k :- prev
			do k :% len
			for j(1, k)
				do n :: f(n)
			end for
			break i
		end if
		do map.add(n, i)
	end for
	
	var ans: int :: n
	do cui@print("\{ans}\n")
	
	func f(n: int): int
		var res: int :: n
		while(n <> 0)
			do res :+ n % 10
			do n :/ 10
		end while
		ret res % 10 ^ 5
	end func
end func
AtCoder problem 058

C++ solution:


Python solution: import sys
def input(): return sys.stdin.readline().strip()
def INTS():  return [ int(s) for s in input().split(" ")]
def log(*args, **kwargs): print("DEBUG:", *args, **kwargs, file=sys.stderr)

class Doubling():
    def __init__(self, n, k_max, f) -> None:
        """要素数nのダブリングテーブルを作成します。"""

        k_bits = k_max.bit_length()

        # dub[i][j] = 値jを2**i回操作した結果
        dub = [[0] * n for _ in range(k_bits)]

        # 1回(2**0回)操作した結果を作成
        for j in range(n):
            dub[0][j] = f(j)

        # 2**i回操作した結果を順に作成
        # 2**(i-1)回操作を2回すれば2**i回操作したことになる
        for i in range(1, k_bits):
            for j in range(n):
                dub[i][j] = dub[i - 1][dub[i - 1][j]]

        self.doubling_table = dub

    def get(self, x, k):
        """xをk回操作した値を取得します。"""
        # kをビットごとに分解して、2**a + 2**b + 2**c + ... の形で考える。
        # xを2**a回操作した結果を2**b回操作した結果を2**c回操作… のように順に適用する
        now = x
        for i in range(k.bit_length()):
            if k>>i & 1:
                now = self.doubling_table[i][now]

        return now

def f(n):
    """(n + nの桁ごとの和) mod 10万 を返します。"""
    s = 0
    x = n
    while x > 0:
        s += x % 10
        x //= 10

    return (n+s) % 100000

def main():
    n, k = INTS()
    dub = Doubling(100000, k, f)
    print(dub.get(n,k))
main()




Kuin solution: func main()
	var n: int :: cui@inputInt()
	var k: int :: cui@inputInt()
	
	var map: dict<int, int> :: #dict<int, int>
	for i(1, k)
		do n :: f(n)
		var prev: int :: map.get(n, &)
		if(prev <> 0)
			var len: int :: i - prev
			do k :- prev
			do k :% len
			for j(1, k)
				do n :: f(n)
			end for
			break i
		end if
		do map.add(n, i)
	end for
	
	var ans: int :: n
	do cui@print("\{ans}\n")
	
	func f(n: int): int
		var res: int :: n
		while(n <> 0)
			do res :+ n % 10
			do n :/ 10
		end while
		ret res % 10 ^ 5
	end func
end func
AtCoder problem 059

C++ solution:
#include <vector>

#include <iostream>

#include <algorithm>

using namespace std;

int main() {

	cin.tie(0);

	ios_base::sync_with_stdio(false);

	int N, M, Q;

	cin >> N >> M >> Q;

	vector<int> X(M), Y(M);

	for (int i = 0; i < M; ++i) {

		cin >> X[i] >> Y[i];

		--X[i], --Y[i];

	}

	vector<long long> g(M);

	for (int i = 0; i < M; ++i) {

		g[i] = 1LL * Y[i] * N + X[i];

	}

	sort(g.begin(), g.end());

	for (int i = 0; i < M; ++i) {

		X[i] = g[i] % N;

		Y[i] = g[i] / N;

	}

	vector<int> A(Q), B(Q);

	for (int i = 0; i < Q; ++i) {

		cin >> A[i] >> B[i];

		--A[i], --B[i];

	}

	for (int i = 0; i * 64 < Q; ++i) {

		vector<unsigned long long> dp(N, 0);

		for (int j = i * 64; j < (i + 1) * 64 && j < Q; ++j) {

			dp[A[j]] |= 1ULL << (j - i * 64);

		}

		for (int j = 0; j < M; ++j) {

			dp[Y[j]] |= dp[X[j]];

		}

		for (int j = i * 64; j < (i + 1) * 64 && j < Q; ++j) {

			cout << (((dp[B[j]] >> (j - i * 64)) & 1) == 1 ? "Yes\n" : "No\n");

		}

	}

	return 0;

}

Crystal solution: n, m, q = read_line.split.map(&.to_i)
edges = (1..m).map {
  {Int32, Int32}.from read_line.split.map(&.to_i.pred)
}.sort_by { |x, y| {y, x} }
ab = (1..q).map {
  {Int32, Int32}.from read_line.split.map(&.to_i.pred)
}

ab.each_slice(128) do |ab|
  flag = [UInt128.zero] * n
  ab.each_with_index { |(a, b), i| flag[a] |= 1.to_u128 << i }
  edges.each { |(x, y)| flag[y] |= flag[x] }
  ab.each_with_index { |(a, b), i| puts flag[b].bit(i) == 1 ? "Yes" : "No" }
end
AtCoder problem 059

C++ solution:
#include <vector>

#include <iostream>

#include <algorithm>

using namespace std;

int main() {

	cin.tie(0);

	ios_base::sync_with_stdio(false);

	int N, M, Q;

	cin >> N >> M >> Q;

	vector<int> X(M), Y(M);

	for (int i = 0; i < M; ++i) {

		cin >> X[i] >> Y[i];

		--X[i], --Y[i];

	}

	vector<long long> g(M);

	for (int i = 0; i < M; ++i) {

		g[i] = 1LL * Y[i] * N + X[i];

	}

	sort(g.begin(), g.end());

	for (int i = 0; i < M; ++i) {

		X[i] = g[i] % N;

		Y[i] = g[i] / N;

	}

	vector<int> A(Q), B(Q);

	for (int i = 0; i < Q; ++i) {

		cin >> A[i] >> B[i];

		--A[i], --B[i];

	}

	for (int i = 0; i * 64 < Q; ++i) {

		vector<unsigned long long> dp(N, 0);

		for (int j = i * 64; j < (i + 1) * 64 && j < Q; ++j) {

			dp[A[j]] |= 1ULL << (j - i * 64);

		}

		for (int j = 0; j < M; ++j) {

			dp[Y[j]] |= dp[X[j]];

		}

		for (int j = i * 64; j < (i + 1) * 64 && j < Q; ++j) {

			cout << (((dp[B[j]] >> (j - i * 64)) & 1) == 1 ? "Yes\n" : "No\n");

		}

	}

	return 0;

}


Python solution: from sys import stdin
pin=stdin.readline
def main():
  N,M,Q=map(int,pin().split())
  G=[[]for _ in[0]*N]
  for _ in[0]*M:
    X,Y=map(int,pin().split())
    G[X-1].append(Y-1)
  d=[]
  c=1
  for _ in[0]*N:
    d.append(c)
    c<<=1
  for i in range(N):
    for j in G[i]:
      d[j]|=d[i]
  for _ in [0]*Q:
    A,B=map(int,pin().split())
    if (d[B-1]>>(A-1))&1:
      print("Yes")
    else:
      print("No")
  return
  
main()
AtCoder problem 059

C++ solution:

Crystal solution: n, m, q = read_line.split.map(&.to_i)
edges = (1..m).map {
  {Int32, Int32}.from read_line.split.map(&.to_i.pred)
}.sort_by { |x, y| {y, x} }
ab = (1..q).map {
  {Int32, Int32}.from read_line.split.map(&.to_i.pred)
}

ab.each_slice(128) do |ab|
  flag = [UInt128.zero] * n
  ab.each_with_index { |(a, b), i| flag[a] |= 1.to_u128 << i }
  edges.each { |(x, y)| flag[y] |= flag[x] }
  ab.each_with_index { |(a, b), i| puts flag[b].bit(i) == 1 ? "Yes" : "No" }
end


Python solution: from sys import stdin
pin=stdin.readline
def main():
  N,M,Q=map(int,pin().split())
  G=[[]for _ in[0]*N]
  for _ in[0]*M:
    X,Y=map(int,pin().split())
    G[X-1].append(Y-1)
  d=[]
  c=1
  for _ in[0]*N:
    d.append(c)
    c<<=1
  for i in range(N):
    for j in G[i]:
      d[j]|=d[i]
  for _ in [0]*Q:
    A,B=map(int,pin().split())
    if (d[B-1]>>(A-1))&1:
      print("Yes")
    else:
      print("No")
  return
  
main()
AtCoder problem 060

C++ solution:
#include <bits/stdc++.h>
using namespace std;
int INF = 1 << 30;

int main()
{
  int N;
  cin >> N;
  vector<int> A(N);
  for (int i = 0; i < N; i++)
  {
    cin >> A.at(i);
    A.at(i) = N + 1 - A.at(i); // 単調減少 → 単調増加 を作る問題にする
  }

  vector<int> dp(N + 2, INF);
  dp.at(0) = -INF;

  for (auto a : A)
  {
    // 通常の LIS で選べる ｢a を使う｣ ｢何もしない｣ に加え ｢-a を使う｣ も選べる, これで単調増加を作る問題になった
    
    auto itmi = lower_bound(dp.begin(), dp.end(), -a);
    auto itpl = lower_bound(dp.begin(), dp.end(), a);

    int imi = itmi - dp.begin(), ipl = itpl - dp.begin();

    if (dp.at(ipl - 1) != -a) dp.at(ipl) = a; // ただし -2, 2 みたいになるとやばいのでそれだけ除外
    dp.at(imi) = -a;
  }

  for (int i = 1; i < N + 2; i++)
  {
    if (dp.at(i) == INF)
    {
      cout << i - 1 << endl;
      return 0;
    }
  }
}


Crystal solution: def lis(a)
  dp = [] of Int32
  a.map do |x|
    if pos = dp.bsearch_index { |y| y >= x }
      dp[pos] = x
      pos + 1
    else
      dp << x
      dp.size
    end
  end
end

read_line
a = read_line.split.map(&.to_i)
lis1, lis2 = lis(a), lis(a.reverse).reverse
puts lis1.zip(lis2).max_of { |x, y| x + y - 1 }
AtCoder problem 060

C++ solution:
#include <bits/stdc++.h>
using namespace std;
int INF = 1 << 30;

int main()
{
  int N;
  cin >> N;
  vector<int> A(N);
  for (int i = 0; i < N; i++)
  {
    cin >> A.at(i);
    A.at(i) = N + 1 - A.at(i); // 単調減少 → 単調増加 を作る問題にする
  }

  vector<int> dp(N + 2, INF);
  dp.at(0) = -INF;

  for (auto a : A)
  {
    // 通常の LIS で選べる ｢a を使う｣ ｢何もしない｣ に加え ｢-a を使う｣ も選べる, これで単調増加を作る問題になった
    
    auto itmi = lower_bound(dp.begin(), dp.end(), -a);
    auto itpl = lower_bound(dp.begin(), dp.end(), a);

    int imi = itmi - dp.begin(), ipl = itpl - dp.begin();

    if (dp.at(ipl - 1) != -a) dp.at(ipl) = a; // ただし -2, 2 みたいになるとやばいのでそれだけ除外
    dp.at(imi) = -a;
  }

  for (int i = 1; i < N + 2; i++)
  {
    if (dp.at(i) == INF)
    {
      cout << i - 1 << endl;
      return 0;
    }
  }
}






Kuin solution: func main()
	var n: int :: cui@inputInt()
	var a: []int :: #[n]int
	for i(0, n - 1)
		do a[i] :: cui@inputInt()
	end for
	
	var ans: int :: solve(a)
	do cui@print("\{ans}\n")
	
	func solve(a: []int): int
		var lis: []int :: getLisArr(a)
		do a.reverse()
		var revLis: []int :: getLisArr(a)
		do revLis.reverse()
		do a.reverse()
		var res: int :: 0
		for i(0, ^a - 1)
			do res :: [res, lis[i] + revLis[i] - 1].max()
		end for
		ret res
		
		func getLisArr(a: []int): []int
			const infInt: int :: lib@intMax
			var n: int :: ^a
			var buff: []int :: [infInt].repeat(n + 1)
			var lisArr: []int :: #[n]int
			for i(0, n - 1)
				var idx: int :: f(buff, a[i])
				do buff[idx] :: a[i]
				do lisArr[i] :: f(buff, infInt)
				
				func f(arr: []int, val: int): int
					var ok: int :: -1
					var ng: int :: ^arr - 1
					while((ok - ng).abs() > 1)
						var mid: int :: (ok + ng) / 2
						if(val > arr[mid])
							do ok :: mid
						else
							do ng :: mid
						end if
					end while
					ret ok + 1
				end func
			end for
			ret lisArr
		end func
	end func
end func
AtCoder problem 060

C++ solution:

Crystal solution: def lis(a)
  dp = [] of Int32
  a.map do |x|
    if pos = dp.bsearch_index { |y| y >= x }
      dp[pos] = x
      pos + 1
    else
      dp << x
      dp.size
    end
  end
end

read_line
a = read_line.split.map(&.to_i)
lis1, lis2 = lis(a), lis(a.reverse).reverse
puts lis1.zip(lis2).max_of { |x, y| x + y - 1 }





Kuin solution: func main()
	var n: int :: cui@inputInt()
	var a: []int :: #[n]int
	for i(0, n - 1)
		do a[i] :: cui@inputInt()
	end for
	
	var ans: int :: solve(a)
	do cui@print("\{ans}\n")
	
	func solve(a: []int): int
		var lis: []int :: getLisArr(a)
		do a.reverse()
		var revLis: []int :: getLisArr(a)
		do revLis.reverse()
		do a.reverse()
		var res: int :: 0
		for i(0, ^a - 1)
			do res :: [res, lis[i] + revLis[i] - 1].max()
		end for
		ret res
		
		func getLisArr(a: []int): []int
			const infInt: int :: lib@intMax
			var n: int :: ^a
			var buff: []int :: [infInt].repeat(n + 1)
			var lisArr: []int :: #[n]int
			for i(0, n - 1)
				var idx: int :: f(buff, a[i])
				do buff[idx] :: a[i]
				do lisArr[i] :: f(buff, infInt)
				
				func f(arr: []int, val: int): int
					var ok: int :: -1
					var ng: int :: ^arr - 1
					while((ok - ng).abs() > 1)
						var mid: int :: (ok + ng) / 2
						if(val > arr[mid])
							do ok :: mid
						else
							do ng :: mid
						end if
					end while
					ret ok + 1
				end func
			end for
			ret lisArr
		end func
	end func
end func
AtCoder problem 061

C++ solution:
#include <iostream>

using namespace std;



int Q, T[1 << 20], X[1 << 20];

int A[1 << 20];

int cl = 500000, cr = 500000;



int main() {

	// Step #1. 入力

	cin >> Q;

	for (int i = 1; i <= Q; i++) cin >> T[i] >> X[i];



	// Step #2. シミュレーション

	for (int i = 1; i <= Q; i++) {

		if (T[i] == 1) {

			cl--;

			A[cl] = X[i];

		}

		if (T[i] == 2) {

			A[cr] = X[i];

			cr++;

		}

		if (T[i] == 3) {

			cout << A[cl + X[i] - 1] << endl;

		}

	}

	return 0;

}

Crystal solution: a = Deque(Int32).new
read_line.to_i.times do
  t, x = read_line.split.map(&.to_i)
  case t
  when 2
    a.push x
  when 1
    a.unshift x
  when 3
    puts a[x - 1]
  end
end
AtCoder problem 061

C++ solution:
#include <iostream>

using namespace std;



int Q, T[1 << 20], X[1 << 20];

int A[1 << 20];

int cl = 500000, cr = 500000;



int main() {

	// Step #1. 入力

	cin >> Q;

	for (int i = 1; i <= Q; i++) cin >> T[i] >> X[i];



	// Step #2. シミュレーション

	for (int i = 1; i <= Q; i++) {

		if (T[i] == 1) {

			cl--;

			A[cl] = X[i];

		}

		if (T[i] == 2) {

			A[cr] = X[i];

			cr++;

		}

		if (T[i] == 3) {

			cout << A[cl + X[i] - 1] << endl;

		}

	}

	return 0;

}


Python solution: """
t = 1 ... xを上に入れる
t = 2 ... xを下に入れる
t = 3 ... 上からx番目のカードを出力
"""
Q = int(input())
from collections import deque
q = deque()
for i in range(Q):
    t, x = map(int,input().split())
    if t == 1:
        q.appendleft(x)
    elif t == 2:
        q.append(x)
    elif t == 3:
        print(q[x - 1])
AtCoder problem 061

C++ solution:
#include <iostream>

using namespace std;



int Q, T[1 << 20], X[1 << 20];

int A[1 << 20];

int cl = 500000, cr = 500000;



int main() {

	// Step #1. 入力

	cin >> Q;

	for (int i = 1; i <= Q; i++) cin >> T[i] >> X[i];



	// Step #2. シミュレーション

	for (int i = 1; i <= Q; i++) {

		if (T[i] == 1) {

			cl--;

			A[cl] = X[i];

		}

		if (T[i] == 2) {

			A[cr] = X[i];

			cr++;

		}

		if (T[i] == 3) {

			cout << A[cl + X[i] - 1] << endl;

		}

	}

	return 0;

}





Kuin solution: func main()
	var q: int :: cui@inputInt()
	var a: []int :: #[2 * 10 ^ 5]int
	var l: int :: 10 ^ 5
	var r: int :: l
	for(1, q)
		var t: int :: cui@inputInt()
		var x: int :: cui@inputInt()
		switch(t)
		case 1
			do l :- 1
			do a[l] :: x
		case 2
			do a[r] :: x
			do r :+ 1
		case 3
			do cui@print("\{a[l + x - 1]}\n")
		end switch
	end for
end func
AtCoder problem 061

C++ solution:

Crystal solution: a = Deque(Int32).new
read_line.to_i.times do
  t, x = read_line.split.map(&.to_i)
  case t
  when 2
    a.push x
  when 1
    a.unshift x
  when 3
    puts a[x - 1]
  end
end


Python solution: """
t = 1 ... xを上に入れる
t = 2 ... xを下に入れる
t = 3 ... 上からx番目のカードを出力
"""
Q = int(input())
from collections import deque
q = deque()
for i in range(Q):
    t, x = map(int,input().split())
    if t == 1:
        q.appendleft(x)
    elif t == 2:
        q.append(x)
    elif t == 3:
        print(q[x - 1])
AtCoder problem 061

C++ solution:

Crystal solution: a = Deque(Int32).new
read_line.to_i.times do
  t, x = read_line.split.map(&.to_i)
  case t
  when 2
    a.push x
  when 1
    a.unshift x
  when 3
    puts a[x - 1]
  end
end





Kuin solution: func main()
	var q: int :: cui@inputInt()
	var a: []int :: #[2 * 10 ^ 5]int
	var l: int :: 10 ^ 5
	var r: int :: l
	for(1, q)
		var t: int :: cui@inputInt()
		var x: int :: cui@inputInt()
		switch(t)
		case 1
			do l :- 1
			do a[l] :: x
		case 2
			do a[r] :: x
			do r :+ 1
		case 3
			do cui@print("\{a[l + x - 1]}\n")
		end switch
	end for
end func
AtCoder problem 061

C++ solution:


Python solution: """
t = 1 ... xを上に入れる
t = 2 ... xを下に入れる
t = 3 ... 上からx番目のカードを出力
"""
Q = int(input())
from collections import deque
q = deque()
for i in range(Q):
    t, x = map(int,input().split())
    if t == 1:
        q.appendleft(x)
    elif t == 2:
        q.append(x)
    elif t == 3:
        print(q[x - 1])



Kuin solution: func main()
	var q: int :: cui@inputInt()
	var a: []int :: #[2 * 10 ^ 5]int
	var l: int :: 10 ^ 5
	var r: int :: l
	for(1, q)
		var t: int :: cui@inputInt()
		var x: int :: cui@inputInt()
		switch(t)
		case 1
			do l :- 1
			do a[l] :: x
		case 2
			do a[r] :: x
			do r :+ 1
		case 3
			do cui@print("\{a[l + x - 1]}\n")
		end switch
	end for
end func
AtCoder problem 062

C++ solution:
#include <iostream>

#include <vector>

#include <queue>

#include <algorithm>

using namespace std;



int N;

int A[1 << 18], B[1 << 18];

bool usable[1 << 18];

vector<int> G[1 << 18];

queue<int> Q;



int main() {

	// Step #1. 入力

	cin >> N;

	for (int i = 1; i <= N; i++) {

		cin >> A[i] >> B[i];

		G[A[i]].push_back(i);

		G[B[i]].push_back(i);

		if (A[i] == i || B[i] == i) {

			usable[i] = true;

			Q.push(i);

		}

	}



	// Step #2. 後ろからシミュレーション

	vector<int> vec;

	while (!Q.empty()) {

		int pos = Q.front(); Q.pop();

		vec.push_back(pos);

		for (int i : G[pos]) {

			if (usable[i] == true) continue;

			usable[i] = true;

			Q.push(i);

		}

	}



	// Step #3. 答えを求める

	reverse(vec.begin(), vec.end());

	if (vec.size() != N) {

		cout << "-1" << endl;

	}

	else {

		for (int i = 0; i < vec.size(); i++) cout << vec[i] << endl;

	}

	return 0;

}

Crystal solution: n = read_line.to_i

graph = Array.new(n) { [] of Int32 }
stack = Deque(Int32).new
done = [false] * n
n.times do |i|
  a, b = read_line.split.map(&.to_i.pred)
  if a == i || b == i
    stack << i
    done[i] = true
  else
    graph[a] << i
    graph[b] << i
  end
end

ans = [] of Int32
while v = stack.pop?
  ans << v
  graph[v].each do |u|
    unless done[u]
      stack << u
      done[u] = true
    end
  end
end
puts done.all? ? ans.reverse.join('\n', &.succ) : -1
AtCoder problem 063

C++ solution:
#include <iostream>

#include <vector>

#include <map>

#include <algorithm>

using namespace std;



int H, W;

int P[19][10009];



int maximum_same(vector<int> R) {

	map<int, int> Map; int ret = 0;

	for (int i = 0; i < R.size(); i++) {

		Map[R[i]] += 1;

		ret = max(ret, Map[R[i]]);

	}

	return ret;

}



int main() {

	// Step #1. “ü—Í

	cin >> H >> W;

	for (int i = 0; i < H; i++) {

		for (int j = 0; j < W; j++) cin >> P[i][j];

	}



	// Step #2. ‘S’T�õ

	int Answer = 0;

	for (int i = 1; i < (1 << H); i++) {

		vector<int> R;

		for (int j = 0; j < W; j++) {

			int idx = -1; bool flag = false;

			for (int k = 0; k < H; k++) {

				if ((i & (1 << k)) == 0) continue;

				if (idx == -1) idx = P[k][j];

				else if (idx != P[k][j]) flag = true;

			}

			if (flag == false) R.push_back(idx);

		}



		int cntH = 0, cntW = maximum_same(R);

		for (int j = 0; j < H; j++) {

			if ((i & (1 << j)) != 0) cntH += 1;

		}

		Answer = max(Answer, cntH * cntW);

	}

	cout << Answer << endl;

	return 0;

}

Crystal solution: h, w = read_line.split.map(&.to_i)
a = (1..h).map { read_line.split.map(&.to_i) }
puts (1...1 << h).max_of { |bit|
  ind = (0...h).select { |i| bit.bit(i) == 1 }
  ((0...w).select { |j|
    ind.all? { |i| a[i][j] == a[ind[0]][j] }
  }.map { |j| a[ind[0]][j] }.tally.max_of?(&.[1]) || 0) * ind.size
}
AtCoder problem 063

C++ solution:
#include <iostream>

#include <vector>

#include <map>

#include <algorithm>

using namespace std;



int H, W;

int P[19][10009];



int maximum_same(vector<int> R) {

	map<int, int> Map; int ret = 0;

	for (int i = 0; i < R.size(); i++) {

		Map[R[i]] += 1;

		ret = max(ret, Map[R[i]]);

	}

	return ret;

}



int main() {

	// Step #1. “ü—Í

	cin >> H >> W;

	for (int i = 0; i < H; i++) {

		for (int j = 0; j < W; j++) cin >> P[i][j];

	}



	// Step #2. ‘S’T�õ

	int Answer = 0;

	for (int i = 1; i < (1 << H); i++) {

		vector<int> R;

		for (int j = 0; j < W; j++) {

			int idx = -1; bool flag = false;

			for (int k = 0; k < H; k++) {

				if ((i & (1 << k)) == 0) continue;

				if (idx == -1) idx = P[k][j];

				else if (idx != P[k][j]) flag = true;

			}

			if (flag == false) R.push_back(idx);

		}



		int cntH = 0, cntW = maximum_same(R);

		for (int j = 0; j < H; j++) {

			if ((i & (1 << j)) != 0) cntH += 1;

		}

		Answer = max(Answer, cntH * cntW);

	}

	cout << Answer << endl;

	return 0;

}


Python solution: from itertools import product
from collections import Counter

def calc(A: list) -> int:
    "良いグリッドを求める"

    # bitの立っている行数を求める
    colum = 0
    for i in range(len(A)):
        if A[i] == 1:
            colum += 1
     
    cnt = Counter()
    for i in range(w):
        num = [] 
        for j in range(h):
            if A[j] == 1:
                num.append(p[j][i])
        # 列に入っている数字が全て同じである時
        if len(set(num)) == 1:
            cnt[num[0]] += 1
   
    return max(cnt.values()) * colum if len(cnt) > 0 else 0

h, w = map(int,input().split())
p = [list(map(int,input().split())) for _ in range(h)]

ans = 0
for bit in product([0, 1], repeat = h):
    ans = max(ans, calc(bit))

print(ans)