jiahuimbzuai/CoQuIR huggingface dataset:
//  [javascript]
"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextssort(n,a){return a?cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>b-a):cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>a-b);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}
var streams=[];function print(s){streams.push(s);}
var mod = 1e9+7;
function mul(){for(var a=arguments,r=a[0],i=a.length;--i;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i])%mod;return r;}
var fac=[],finv=[],invs=[],pow2=[];
function fset(n){
  fac.length=n+1,fac[0]=fac[1]=1;
  for(var i=2;i<=n;)fac[i]=mul(fac[i-1],i++);
  finv.length=n+1,finv[0]=finv[1]=1,finv[n]=inv(fac[n]);
  for(i=n;2<i;)finv[i-1]=mul(finv[i],i--);
  //invs.length=n+1,invs[0]=invs[1]=1;
  //for(i=2;i<=n;)invs[i]=mul(fac[i-1],finv[i++]);
  //pow2.length=n+1,pow2[0]=1;
  //for(i=1;i<=n;i++)pow2[i]=pow2[i-1]*2%mod;
}
function inv(b){for(var a=mod,u=0,v=1,t;b;v=t)t=a/b|0,a-=t*b,u-=t*v,t=a,a=b,b=t,t=u,u=v;u%=mod;return u<0?u+mod:u;}
function pow(a,n){for(var r=1;n;a=mul(a,a),n>>=1)if(n&1)r=mul(a,r);return r;}
function ncr(n,r){return mul(fac[n],finv[r],finv[n-r]);}
function npr(n,r){return mul(fac[n],finv[n-r]);}
function mput(n){return (n%mod+mod)%mod;}


var myOut = main();
if(myOut !== undefined)console.log(String(myOut));
if(streams.length)console.log(streams.join("\n"));

function main(){
  var s = next();
  var dp = xArray(0,s+1);
  dp[0] = 1;
  for(var i = 0; i < s; i++){
    for(var j = 3; j <= s; j++){
      if(i+j > s)break;
      dp[i+j] += dp[i];
      dp[i+j] %= mod;
    }
  }
  return dp[s];
}
//  [javascript]
const main = (input) => {
  const mod = (10**9 + 7)
  const s = Number(input.trim())

  const dp = [1, ...new Array(s).fill(0)]

  for (let x=3; x<dp.length; x++) {
    let sum = 0

    for (let i=x-3; i>=0; i--) {
      sum = (sum + dp[i]) % mod
    }

    dp[x] = sum
  }

  return console.log((dp[s] % mod + mod) % mod)
}

process.env.MYTEST
  ? (process.env.MYTEST === 'test' ? test() : main(require('fs').readFileSync('dev/stdin', 'utf8')))
  : main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('utf-8');
 
let inputString = '';
let currentLine = 0;
 
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
 
process.stdin.on('end', _ => {
    inputString = inputString.split(/\n/);
    main();    
});
 
function readLine() {
    return inputString[currentLine++];
}

const mod = Math.pow(10, 9) + 7
function main() {
  const s = Number(readLine())
  let maxLength = Math.floor(s / 3)
  let result = 0
  const { fac, finv } = comInit(s)
  for (let l = 1; l <= maxLength; l++) {
    const remain = s - l * 3
    result += com(remain + l - 1, l - 1, fac, finv)
    result %= mod
  }
  console.log(result)
}

function comInit(l) {
  let fac = [1n, 1n]
  let finv = [1n, 1n]
  let inv = [0n, 1n]
  const biMod = BigInt(mod)
  for (let i = 2; i <= l; i++){
    const biI = BigInt(i)
    fac[i] = fac[i - 1] * biI % biMod;
    inv[i] = biMod - inv[biMod % biI] * (biMod / biI) % biMod;
    finv[i] = finv[i - 1] * inv[i] % biMod;
  }
  return { fac, finv }
}

function com(n, k, fac, finv){
  if (n < k) return 0;
  if (n < 0 || k < 0) return 0;
  const biMod = BigInt(mod)
  return Number(fac[n] * (finv[k] * finv[n - k] % biMod) % biMod);
}
//  [javascript]
function seqs(n) {
	let num = Number(n);
  	let count = 0;
  	if(num < 3) {
		return count;
	} else {
	for(let i = 3; i < num; i++) {
		if(num - i > 3)
          count++;
		}
    }
  	return count%(10**9 + 7);
]

console.log(seqs(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [javascript]
function Main(input) {
	const amari = Math.pow(10, 9) + 7;
}

// Main(require("fs").readFileSync("sample.txt", "utf8"));  // テスト用
Main(require("fs").readFileSync("/dev/stdin", "utf8"));   // 提出用
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	var s, a int
	a = int(math.Pow(10, 9)) + 7
	fmt.Scan(&s)
	A := make([]int, 2001)
	A[0] = 1
	A[1] = 0
	A[2] = 0
	var i = 3
	for ; i <= s; i++ {
		A[i] = (A[i-1] + A[i-3]) % a
	}
	i--
	var ans = A[i] % a
	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
)

const mod = 1000000007

func main() {
	var s int
	fmt.Scan(&s)
	dp := make([]int, s+1)
	dp[0] = 1
	for i := 1; i <= s; i++ {
		if i < 3 {
			dp[i] = 0
			continue
		}
		dp[i] = dp[i-1] + dp[i-3]
		dp[i] %= mod
	}
	ans := dp[s]
	ans %= mod
	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	mod := 1000000007
	var s int
	fmt.Scan(&s)

	dp := make([]int , s+1)
	dp[0] = 1
	for i := 1; i < s+1; i++{
		for j := 0; j < (i-3)+1; j++ {
			dp[i] += dp[j]
			dp[i] = dp[i]%mod
		}
	}
	println(dp[s])

}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const mod int = 1e9 + 7

var s int

func main() {
	readVariables()
	fmt.Println(solve2(s))
	// for i := 1; i <= s; i++ {
	// 	if solve1(s) != solve2(s) {
	// 		fmt.Println(s, solve1(s), solve2(s))
	// 	}
	// }
}

// O(S^2)
func solve1(s int) int {
	var dp [3000]int
	dp[0] = 1
	for i := 1; i <= s; i++ {
		for j := 3; i-j >= 0; j++ {
			dp[i] += dp[i-j]
		}
		dp[i] %= mod
	}
	answer := dp[s]
	return answer
}

// intended O(S)
func solve2(s int) int {
	var dp [3000]int
	dp[0] = 1
	get := func(i int) int {
		if i < 0 {
			return 0
		}
		return dp[i]
	}
	for i := 1; i <= s; i++ {
		dp[i] = dp[i-1] + get(i-3)
		dp[i] %= mod
	}
	answer := get(s) - get(s-1)
	return answer
}

func readVariables() {
	s = nextInt()

}

/* Template */

var scanner *bufio.Scanner

func init() {
	Max := 1001001
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 0, Max), Max)
	scanner.Split(bufio.ScanWords)
}

//nextInt converts next token from stdin and returns integer value.
//nextInt panics when conversion into an integer fails.
func nextInt() int {
	if !scanner.Scan() {
		panic("No more token.")
	}
	num, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic("nextInt(): cannot convert to int: " + scanner.Text())
	}
	return num
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var dp [3000]int
var s int

const mod int = 1e9 + 7

func main() {
	readVariables()
	dp[0] = 1
	for i := 1; i <= s; i++ {
		dp[i] = dp[i-1] + get(i-3)
		dp[i] %= mod
	}
	answer := get(s) - get(s-1)
	fmt.Println(answer)
}

func get(i int) int {
	if i < 0 {
		return 0
	}
	return dp[i]
}

func readVariables() {
	s = nextInt()

}

/* Template */

var scanner *bufio.Scanner

func init() {
	Max := 1001001
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 0, Max), Max)
	scanner.Split(bufio.ScanWords)
}

//nextInt converts next token from stdin and returns integer value.
//nextInt panics when conversion into an integer fails.
func nextInt() int {
	if !scanner.Scan() {
		panic("No more token.")
	}
	num, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic("nextInt(): cannot convert to int: " + scanner.Text())
	}
	return num
}
//  [ruby]
D,M=[t=0]*3,10**9+7
0.upto(gets.to_i){D[_1+3]=1+t+=D[_1]}
p D[-4]%M
//  [ruby]
s = gets.to_i
dp = [0]*(s+1)
dp[0] = 1
x = 0
(3..s).each do |i|
  x += dp[i-3]
  x %= 10**9+7
  dp[i] = x
end
puts dp[s]
//  [ruby]
s = gets.to_i
m = 10 ** 9 + 7
d = [1, 0, 0]
(3..s).each do
  d << (d.last + d.shift) % m
end
puts d.last
//  [ruby]
D,M = [],10**9+7
3.upto(S=gets.to_i) {|s| D[s] = (3..s-3).sum(1){D[_1]} }
p D[S]%M
//  [ruby]
D,M = [],10**9+7
S = gets.to_i
3.upto(S) { D[s] = (3..s-3).sum(1){D[_1]} }
p D[S]%M
//  [ruby]
def C(n,k)
  if n==1
    return 1
  elsif k==0 || k==n
    return 1
  else
    return C(n-1,k-1)+C(n-1,k)
  end
end
#重複組み合わせ
#n個の異なるものからr個取ってくる・・・H(n,r)とおく
def H(n,r)
  return C(n+r-1,r)
end

#以下本題
n = gets.to_i
t = n/3 #１からtまで
sum = 0
for k in 1..t
  sum += H(k,n-3*k)
end
puts sum%(10**9+7)
//  [rust]
#![allow(unused_imports, non_snake_case, dead_code)]
use proconio::{
    input, fastout,
    marker::{Chars, Bytes, Usize1}
};

const MODULO: u64 = 1_000_000_007;

struct Combination {
    MOD: u64,
    size: usize,
    fact: Vec<u64>,
    inv_fact: Vec<u64>,
}
impl Combination {
    fn new(size: usize, MOD: u64) -> Self {
        let mut fact = vec![1; size + 1];
        let mut inv_fact = vec![1; size + 1];
        for i in 1..size + 1 {
            fact[i] = fact[i - 1] * i as u64 % MOD;
        }
        inv_fact[size] = Self::modpow(fact[size], MOD - 2, MOD);
        for i in (1..size + 1).rev() {
            inv_fact[i - 1] = inv_fact[i] * i as u64 % MOD;
        }
        Combination {
            MOD,
            size,
            fact,
            inv_fact,
        }
    }
    fn modpow(mut x: u64, mut y: u64, m: u64) -> u64 {
        let mut res: u64 = 1;
        while y > 0 {
            if y & 1 > 0 {
                res = res * x % m;
            }
            x = x * x % m;
            y >>= 1;
        }
        res
    }
    fn modinv(x: u64, m: u64) -> u64 {
        Self::modpow(x, m - 2, m)
    }
    fn nPr(&self, n: usize, r: usize) -> u64 {
        if n < r {
            return 0;
        };
        self.fact[n] * self.inv_fact[n - r] % self.MOD
    }
    fn nCr(&self, n: usize, r: usize) -> u64 {
        if n < r {
            return 0;
        };
        self.fact[n] * self.inv_fact[r] % self.MOD * self.inv_fact[n - r] % self.MOD
    }
}

#[fastout]
fn main() {
    input!{
        N: usize
    }
    let ncr = Combination::new(N * 2, MODULO);
    let mut ans = 0;
    for i in 1..N/3+1 {
        ans = (ans + ncr.nCr(N-i*3+i-1, i-1)) % MODULO;
    }
    println!("{}", ans);

}
//  [rust]
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::HashMap;
#[allow(unused_imports)]
use std::collections::VecDeque;
#[allow(unused_imports)]
use std::io::*;
#[allow(unused_imports)]
use std::mem::*;
#[allow(unused_imports)]
use std::str::*;
#[allow(unused_imports)]
use std::usize;

#[allow(unused_macros)]
macro_rules! read_cols {
    ($($t:ty),+) => {{
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();

        let mut it = line.trim()
            .split_whitespace();

        ($(
            it.next().unwrap().parse::<$t>().ok().unwrap()
        ),+)
    }}
}

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();
    line.trim().to_string().parse().ok().unwrap()
}

#[allow(dead_code)]
fn read_vec<T: FromStr>() -> Vec<T> {
    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();

    line.trim()
        .split_whitespace()
        .map(|s| s.parse().ok().unwrap())
        .collect()
}

const M: i64 = 1000000007;

fn main() {
    let s: i64 = read();

    let mut fact = vec![1, 1];
    let mut ifact = vec![1, 1];
    let mut inv = vec![1, 1];
    for i in 2..=4000i64 {
        fact.push(fact.last().unwrap() * i % M);
        inv.push((M - (M / i) * inv[(M % i) as usize] % M) % M);
        ifact.push(ifact.last().unwrap() * inv.last().unwrap() % M);
    }

    let combi =
        |n: i64, m: i64| fact[n as usize] * ifact[(n - m) as usize] % M * ifact[m as usize] % M;

    let ans = (1..=2000)
        .take_while(|n| 3 * n <= s)
        .map(|n| {
            let ss = s - n * 3;

            // println!("{} {}", n, combi(ss + n - 1, n - 1));
            combi(ss + n - 1, n - 1)
        })
        .fold(0, |acc, a| (acc + a) % M);

    println!("{}", ans);
}
//  [rust]
// -*- coding:utf-8-unix -*-

use proconio::input;

// n^p mod m (繰り返し二乗法)
fn repeat_square(n: u64, p: u64, m: u64) -> u64 {
    if p == 0 {
        1
    } else if p == 1 {
        n % m
    } else if p % 2 == 0 {
        repeat_square(n, p / 2, m).pow(2) % m
    } else {
        (n * repeat_square(n, p - 1, m)) % m
    }
}

fn ncr_mod(n: u64, r: u64, m: u64) -> u64 {
    let mut denominator = n;
    let mut numerator = 1;
    for i in 1..r {
        denominator = (denominator * (n - i)) % m;
        numerator = (numerator * (i + 1)) % m;
    }
    (denominator * repeat_square(numerator, m - 2, m)) % m
}

fn main() {
    input! {
        s: u64,
    }

    let divisor = 10_u64.pow(9) + 7;
    let mut ans = 0;
    // 項の数が i (すべての項は 3 以上)
    for i in 1..s {
        if 3 * i > s {
            break;
        }

        let needed = s - (3 * i);
        ans += ncr_mod(i + needed - 1, needed, divisor);
        ans = ans % divisor;
    }
    println!("{}", ans);
}
//  [swift]
let s = Int(readLine()!)!
let devider = 1000_000_000 + 7
var dpTable: [Int] = .init(repeating: 0, count: s+1)

dpTable[0] = 1
dpTable[1] = 0
dpTable[2] = 0

if s >= 3 {
    for i in 3...s {
        dpTable[i] = dpTable[i-3]+dpTable[i-1]
        dpTable[i] %= devider
    }
}

print(dpTable[s])
//  [swift]
let s = Int(readLine()!)!

var dp: [Int] = .init(repeating: -1, count: s + 1)
let mod = 1000000007
func backtrack(from value: Int, target: Int) -> Int {
  if value == target {
    return 1
  }
  if value > target {
    return 0
  }
  if dp[value] != -1 {
    return dp[value]
  }
  
  var sum = 0
  for i in 3..<2001 {
    if i + value > target {
      break
    }
    sum += backtrack(from: value + i, target: target)
    sum %= mod
  }
  dp[value] = sum
  return dp[value]
}

print(backtrack(from: 0, target: s))
//  [swift]
let s = Int(readLine()!)!

var dp: [Int] = .init(repeating: -1, count: s + 1)
let mod = 1000000007
func backtrack(from value: Int, target: Int) -> Int {
  if value == target {
    return 1
  }
  if value > target {
    return 0
  }
  if dp[value] != -1 {
    return dp[value]
  }
  
  var sum = 0
  for i in 3..<2000 {
    if i + value > target {
      break
    }
    sum += backtrack(from: value + i, target: target)
    sum %= mod
  }
  dp[value] = sum
  return dp[value]
}

print(backtrack(from: 0, target: s))
//  [swift]
let s = Int(readLine()!)!
let devider = 1000_000_000 + 7
var dpTable: [Int] = .init(repeating: 0, count: s+1)

dpTable[0] = 1
dpTable[1] = 0
dpTable[2] = 0


for i in 3...s {
    dpTable[i] = dpTable[i-3]+dpTable[i-1]
    dpTable[i] %= devider
}

print(dpTable[s])
//  [swift]
let s = Int(readLine()!)!
let devider = 1000_000_000 + 7
var dpTable: [Int] = .init(repeating: 0, count: s+1)

dpTable[0] = 1
dpTable[1] = 0
dpTable[2] = 0


for i in 3...s {
    for j in 0...i-3 {
        dpTable[i] += dpTable[j]
        dpTable[i] %= devider
    }
}

print(dpTable[s])
//  [typescript]
var main = (input: string) => {
    const s: number = parseInt(input);

    let ans: number = distribution(s) % 1000000007;
    ans = (ans + 1000000007) % 1000000007;
    console.log(ans);
}

var memorizedDistribution = {};
function distribution(s: number) {
    if (s === 1 || s === 2) {
        return 0;
    } else if (s === 3) {
        return 1;
    }

    if (memorizedDistribution[s]) {
        return memorizedDistribution[s];
    } else {
        let d = (distribution(s - 1) + distribution(s - 3)) % 1000000007;
        memorizedDistribution[s] = d;
        return d;
    }
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [python]
Cards=[input() for _ in range(3)]
start=0
while Cards[start]:
  turn=ord(Cards[start][0])-97
  Cards[start]=Cards[start][1:]
  start=turn
print(chr(turn+97).upper())
//  [python]
import sys
A=str(input())
B=str(input())
C=str(input())
 
alt="a"
while True:
  if alt == "a":
    if A=="":
      print("A")
      sys.exit()
    alt = A[0]
    A=A[1:]
  if alt == "b":
    if B=="":
      print("B")
      sys.exit()
    alt = B[0]
    B=B[1:]
  if alt == "c":
    if C=="":
      print("C")
      sys.exit()
    alt = C[0]
    C=C[1:]
//  [python]
s = {'a':input(),'b':input(),'c':input()}
n = 'a'
while len(s[n])!= 0:
    o = s[n][0]
    s[n] = s[n][1:]
    n = o
print(n.upper())
//  [python]
s_a = input()
s_b = input()
s_c = input()
turn = str()
isCalledOnce = True

turn = s_a[0]
s_a = s_a.lstrip(turn)

while len(s_a) >= 1 and len(s_b) >= 1 and len(s_c) >= 1:
    if turn == "a" and isCalledOnce:
        s_a = s_a.lstrip(s_a[0])
        if len(s_a) == 0:
            break
        turn = s_a[0]
        isCalledOnce = False
    if turn == "b" and isCalledOnce:
        s_b = s_b.lstrip(s_b[0])
        if len(s_b) == 0:
            break
        turn = s_b[0]
        isCalledOnce = False
    if turn == "c" and isCalledOnce:
        s_c = s_c.lstrip(s_c[0])
        if len(s_b) == 0:
            break
        turn = s_c[0]
        isCalledOnce = False
    
    isCalledOnce = True

if turn == "a":
    print("A")
if turn == "b":
    print("B")
if turn == "c":
    print("C")
//  [python]
s_a = input()
s_b = input()
s_c = input()
turn = str()
isCalledOnce = True

turn = s_a[0]
s_a = s_a.lstrip(turn)

while len(s_a) >= 1 and len(s_b) >= 1 and len(s_c) >= 1:
    if turn == "a" and isCalledOnce:
        turn = s_a[0]
        s_a = s_a.lstrip(turn)
        isCalledOnce = False
    if turn == "b" and isCalledOnce:
        turn = s_b[0]
        s_b = s_b.lstrip(turn)
        isCalledOnce = False
    if turn == "c":
        turn = s_c[0]
        s_c = s_c.lstrip(turn)
    
    isCalledOnce = True

if turn == "a":
    print("A")
if turn == "b":
    print("B")
if turn == "c":
    print("C")
//  [python]
s_a = input()
s_b = input()
s_c = input()
turn = str()

turn = s_a[0]
s_a = s_a.lstrip(turn)

while len(s_a) >= 1 and len(s_b) >= 1 and len(s_c) >= 1:
    if turn == "a":
        turn = s_a[0]
        s_a = s_a.lstrip(turn)
    if turn == "b":
        turn = s_b[0]
        s_b = s_b.lstrip(turn)
    if turn == "c":
        turn = s_c[0]
        s_c = s_c.lstrip(turn)

if turn == "a":
    print("A")
if turn == "b":
    print("B")
if turn == "c":
    print("C")
//  [java]
import java.util.*;
import java.io.*;
import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		
		// 入力
		String a = sc.next();
		String b = sc.next();
		String c = sc.next();
		
		// 計算
		String result = "";
		int ia = 0;
		int ib = 0;
		int ic = 0;
		char next = 'a';
		while(true){
		    if(next == 'a'){
		        if(ia == a.length()){
		            result = "A";
		            break;
		        }else{
		            next = a.charAt(ia);
		            ia++;
		        }
		    }else if(next == 'b'){
		        if(ib == b.length()){
		            result = "B";
		            break;
		        }else{
		            next = b.charAt(ib);
		            ib++;
		        }
		    }else{
		        if(ic == c.length()){
		            result = "C";
		            break;
		        }else{
		            next = c.charAt(ic);
		            ic++;
		        }
		    }
		}
		
		// 出力
		System.out.println(result);
	}
	
	public static class Scanner {
		private BufferedReader br; private StringTokenizer tok;
		public Scanner(InputStream is) throws IOException { br = new BufferedReader(new InputStreamReader(is));}
		private void getLine() throws IOException { while(!hasNext()) tok = new StringTokenizer(br.readLine());}
		private boolean hasNext() { return tok != null && tok.hasMoreTokens();}
		public String next() throws IOException { getLine(); return tok.nextToken();}
		public int nextInt() throws IOException { return Integer.parseInt(next());}
		public long nextLong() throws IOException { return Long.parseLong(next());}
		public double nextDouble() throws IOException { return Double.parseDouble(next());}
	}
}
//  [java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public final class Main {
	public static void main(String[] args) throws java.lang.Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder a = new StringBuilder(br.readLine());
		StringBuilder b = new StringBuilder(br.readLine());
		StringBuilder c = new StringBuilder(br.readLine());
		Solver s = new Solver();
		System.out.println(s.solve(a, b, c));
	}

}

class Solver {

	String solve(StringBuilder a, StringBuilder b, StringBuilder c) {
		char t = 'a';
		while (true) {
			if (t == 'a') {
				if (a.length() == 0) {
					return "A";
				}
				t = a.charAt(0);
				a.deleteCharAt(0);
			} else if (t == 'b') {

				if (b.length() == 0) {
					return "B";
				}
				t = b.charAt(0);
				b.deleteCharAt(0);
			} else if (t == 'c') {

				if (c.length() == 0) {
					return "C";
				}
				t = c.charAt(0);
				c.deleteCharAt(0);
			}
		}

	}

}
//  [java]
import java.io.*;
import java.util.*;

class Main {
    static char[] a, b, c;
    static int[] ids;
    static char res;
    
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        ids = new int[3];
        a = br.readLine().toCharArray();
        b = br.readLine().toCharArray();
        c = br.readLine().toCharArray();
        recur(0, a);
        System.out.println(res);
    }
    
    static void recur(int id, char[] carr){
        if(ids[id]==carr.length){
            res = (char)(id+'A');
            return;
        }
        char curr = carr[ids[id]];
        ids[id]++;
        if(curr == 'a')
            recur(0, a);
        else if(curr == 'b')
            recur(1, b);
        else
            recur(2, c);
    }
}
//  [cpp]
#include <stdio.h>

int main(int argc, char **argv)
{
	int i , acnt = 0, bcnt = 0, ccnt = 0;
	char cards[3][300] = { 0 };
	char turn = 'a';

	for (i = 0; i < 3; i++) {
		scanf("%s", cards[i]);
	}
	for (;;) {
		if (turn == 'a') {
			turn = cards[0][acnt];
			if (!turn) {
				printf("A\r\n");
				break;
			}
			acnt++;
		} else if (turn == 'b') {
			turn = cards[1][bcnt];
			if (!turn) {
				printf("B\r\n");
				break;
			}
			bcnt++;
		} else {
			turn = cards[2][ccnt];
			if (!turn) {
				printf("C\r\n");
				break;
			}
			ccnt++;
		}
	}

	return 0;
}
//  [cpp]
#include<stdio.h>

#define PEOPLE_MAX 3
#define MAX_LENGTH 101
int main(int argc, char *argv[])
{
	int i, turn = 0;
	int position[PEOPLE_MAX] = {0};
	char s[PEOPLE_MAX][MAX_LENGTH];
	
	for (i = 0; i < PEOPLE_MAX; ++i) {
		scanf("%s", s[i]);
	}
	
	while(1) {
		++position[turn];
		turn = s[turn][position[turn] - 1] - 97;
		if (s[turn][position[turn]] == '\0') {
			break;
		}
	}
	printf("%c\n", turn + 65);
	
	return 0;
}
//  [cpp]
#include<stdio.h>
#include<string.h>
int main(void)
{
	char a[3][100];
	int x,y,i,w[3],j,p[3];
	for(i=0;i<3;i++) w[i]=0;
	for(i=0;i<3;i++){
		scanf("%s",a[i]); w[i]=strlen(a[i]); p[i]=0;
	}	
	x=0;
	while(1){
		y=a[x][p[x]]-'a';
		p[x]++;
		x=y;
		if(p[x]==w[x]) break;
	}
	printf("%c\n",x+'A');
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ll long long
int main(){
  string sa,sb,sc;
  cin >> sa >> sb >> sc;
  ll la=sa.size(),lb=sb.size(),lc=sc.size();
  char ch='a';
  ll a=0,b=0,c=0;
  while(1){
    if(ch=='a'&& a>=la){
       cout << 'A';
      break;
      return 0;
    }
    if(ch=='b'&& b>=lb){
       cout << 'B';
      break;
      return 0;
    }
    if(ch=='c'&& c>=lc){
       cout << 'C';
      break;
      return 0;
    }
    if(ch=='a'){
      ch=sa.at(a);
      a++;
    }else if(c=='b'){
      ch=sb.at(b);
      b++;
    }else{
      ch=sc.at(c);
      c++;
    }
    
  }
}
//  [cpp]
#include <iostream>
#include <string>
#include <vector>

using namespace std;


class Solution{

public:
    char winner(const vector<string>& s){

        char cur = 'a';
        vector<int> p(3, 0);
        while(p[cur - 'a'] < s[cur - 'a'].size()){
            cur = s[cur - 'a'][p[cur - 'a']];
            p[cur - 'a'] ++;
        }
        return cur - 'a' + 'A';
    }
};

int main() {

    vector<string> s(3);
    for(int i = 0; i < 3; i ++) cin >> s[i];
    printf("%c\n", Solution().winner(s));

    return 0;
}
//  [cpp]
#include <iostream>
#include <string>
using namespace std;
string Sa,Sb,Sc;
int a_cnt = 0;
int b_cnt = 0;
int c_cnt = 0;
string ans = "A";

void make_turn(char id){
    if(id == 'a'){
    	if(a_cnt < Sa.size()){
    	    a_cnt++;
    	    make_turn(Sa[a_cnt-1]);
    		}
    	else{
    	    ans = "A";
    		}
    	}
    else if(id == 'b' ){
    	if(b_cnt < Sb.size()){
    	    b_cnt++;
    	    make_turn(Sb[b_cnt-1]);
    	    }
    	else{
    	    ans = "B";
    		}
    	    
    	}
    else if(id == 'c'){
    	if(c_cnt < Sb.size()){
    	    c_cnt++;
        	make_turn(Sc[c_cnt-1]);
         }
    	else{
    	    ans = "C";
    		}	
    	}
	}

int main(){
	
	cin >> Sa >> Sb >> Sc;
	
	make_turn('a');
	
	cout << ans << endl;
		
		
	return 0;
	}
//  [c]
short len[3], used[3], s[3][100], d, i;

void rec(t){
        if(used[t]++>=len[t]) putchar('A'+t);
        else rec(s[t][used[t]-1]);
}

main(){
        for(i=0; i<3; i++){
                while((d=getchar())!='\n'){
                        s[i][len[i]++] = d-'a';
                }
        }
        rec(0);
}
//  [c]
#include<stdio.h>
#include<string.h>

int main(){
int a,b,c;
char x;
  char Sa[100],Sb[100],Sc[100];
  scanf("%s",Sa);
  scanf("%s",Sb);
  scanf("%s",Sc);
  a = strlen(Sa);
  b = strlen(Sb);
  c = strlen(Sc);
  x = Sa[0];
  a--;
  while(1){
    if(a == -1 || b == -1 || c == -1){
      break;
    }
    if(x == 'a'){
      if(a > 0){
        x = Sa[strlen(Sa)-a];
      }a--;
  }
    if(x == 'b'){
      if(b > 0){
        x = Sb[strlen(Sb)-b];
      }
      b--;
  }
    if(x == 'c'){
     if(c > 0){
       x = Sc[strlen(Sc)-c];
     }
      c--;
  }
  }
  if(a == -1){
    printf("A");
  }
  if(b == -1){
    printf("B");
  }
  if(c == -1){
    printf("C");
  }
  return 0;
}
//  [c]
char len[3], used[3], s[3][100], d, i;

void rec(char t){
        if(used[t]++>=len[t]) putchar('A'+t);
        else rec(s[t][used[t]-1]);
}

int main(){
        for(i=0; i<3; i++){
                while((d=getchar())!='\n'){
                        s[i][len[i]++] = d-'a';
                }
        }
        rec(0);
        return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>

int main(){
    char a[100],b[100],c[100];
    scanf("%s",a);
    scanf("%s",b);
    scanf("%s",c);
    int sa=strlen(a);
    int sb=strlen(b);
    int sc=strlen(c);

    char s[3][100];
    for(int t=0;t<100;t++){
        s[0][t]=a[t];
        s[1][t]=b[t];
        s[2][t]=c[t];   
    }

    int x=0;
    int y=0;

    int i=0;
    int j=0;
    int k=0;
    for(;;){
        if(s[x][y]=='a'){
            if(x==0){
                i++;
            }else if(x==1){
                j++;
            }else if(x==2){
                k++;
            }
            x=0;
            y=i;
        }else if(s[x][y]=='b'){
            if(x==0){
                i++;
            }else if(x==1){
                j++;
            }else if(x==2){
                k++;
            }
            x=1;
            y=j;
        }else if(s[x][y]=='c'){
            if(x==0){
                i++;
            }else if(x==1){
                j++;
            }else if(x==2){
                k++;
            }
            x=2;
            y=k;
        }else{
            break;
        }
    }

    if(i==sa){
        printf("A\n");
    }else if(j==sb){
        printf("B\n");
    }else if(k==sc){
        printf("C\n");
    }
    return 0;
}
//  [c]
#include<stdio.h>
int main(){
    char Sa[101],Sb[101],Sc[101];
    int i=0,j=0,k=0;
    char p='a';
    scanf("%s",Sa);
    scanf("%s",Sb);
    scanf("%s",Sc);
    while(1){
        switch(p){
            case 'a':{
                if(Sa[i]=='a')p='a';
                else if(Sa[i]=='b')p='b';
                else p='c';
                i++; break;
            }
            case 'b':{
                if(Sb[j]=='a')p='a';
                else if(Sb[j]=='b')p='b';
                else p='c';
                j++; break;
            }
            case 'c':{
                if(Sc[k]=='a')p='a';
                else if(Sc[k]=='b')p='b';
                else p='c';
                k++; break;
            }
        }
        if(Sa[i]=='\0'){
            printf("A");
            break;
        }else if(Sb[j]=='\0'){
            printf("B");
            break;
        }else if(Sc[k]=='\0'){
            printf("C");
            break;
        }
    }
    return 0;
}
//  [javascript]
'use strict'

const main = input => {
	const args = input.split('\n').map(arg => arg.split(' '))

	const t = {
		a: args[0][0].split(''),
		b: args[1][0].split(''),
		c: args[2][0].split('')
	}

	let next = 'a'

	while (true) {
		if (t[next].length === 0) break
		next = t[next].shift()
	}

	console.log(next.toUpperCase())
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
function Main(input) {
	input = input.split("\n");
	input[0] = input[0].split("");
	input[1] = input[1].split("");
	input[2] = input[2].split("");
  input[0].push("#");
    input[1].push("#");
    input[2].push("#");
	var now = 0;
	var ans = "C";
  //console.log(input[now])
	while(input[now].length>0){
		switch(input[now][0]){
			case "a":
			input[now].shift();
			now = 0;
			break;
         	case "b":
			input[now].shift();
			now = 1;
			break;
			case "c":
			input[now].shift();
			now = 2;
			break;
          case "#":
            switch(now){
              case 0:
                console.log("A");
                break;
              case 1:
                console.log("B");
                break;
              case 2:
                console.log("C");
                break;
                      }
            input[now].shift();
            break;
		}
	}
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [javascript]
function Main(arg) 
{
  var sa = arg.split("\n")[0].split("");
  var sb = arg.split("\n")[1].split("");
  var sc = arg.split("\n")[2].split("");

  var next = 'a';
  while (1) {
    if (next === 'a') {
      if (sa.length===0) {
        console.log("A");
        return;
      }
      next = sa.shift();
    }
    else if (next === 'b') {
      if (sb.length===0) {
        console.log("B");
        return;
      }
      next = sb.shift();
    }
    else if (next === 'c') {
      if (sc.length===0) {
        console.log("C");
        return;
      }
      next = sc.shift();
    }
  }

  return;
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let s = {}
    s["a"] = next()
    s['b'] = next()
    s['c'] = next()
    let p = {
        "a" : -1,
        "b" : 0, 
        "c" : 0
    }
    let turn = "a"
    while(true){
        p[turn]++
        if(p[turn] > s[turn].length){
            console.log(turn.toUpperCase())
            return
        }
        turn = s[turn][p[turn]]
    }

}
Main()
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let s = {}
    s["a"] = next()
    s['b'] = next()
    s['c'] = next()
    let p = {
        "a" : -1,
        "b" : 0, 
        "c" : 0
    }
    let turn = "a"
    while(true){
        p[turn]++
        if(p[turn] >= s[turn].length){
            console.log(turn.toUpperCase())
            return
        }
        turn = s[turn][p[turn]]
    }

}
Main()
//  [javascript]
'use strict';

function Main(input) {
  const tmp = input.split('\n');
  const A = tmp[0].split('').reverse();
  const B = tmp[1].split('').reverse();
  const C = tmp[2].split('').reverse();

  let winner;
  let turn = 1;
  let next = A.pop();
  while (turn) {
    switch (next) {
      case 'a':
        next = A.pop();
        if (next == undefined) {
          winner = 'A';
          turn = 0;
        }
        break;
      case 'b':
        next = B.pop();
        if (next == undefined) {
          winner = 'B';
          turn = 0;
        }
      case 'c':
        next = C.pop();
        if (next == undefined) {
          winner = 'C';
          turn = 0;
        }
      default:
        break;
    }
  }
  console.log(winner);
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import "fmt"
import "strings"

func main() {
	var ia, ib, ic string
	fmt.Scan(&ia)
	fmt.Scan(&ib)
	fmt.Scan(&ic)

	sa := strings.Split(ia, "")
	sb := strings.Split(ib, "")
	sc := strings.Split(ic, "")

	turn := "a"
	for {
		switch turn {
		case "a":
			l := len(sa)
			if l > 0 {
				turn = sa[0]
				sa = sa[1:l]
			} else {
				fmt.Println("A")
				return
			}
		case "b":
			l := len(sb)
			if l > 0 {
				turn = sb[0]
				sb = sb[1:l]
			} else {
				fmt.Println("B")
				return
			}
		case "c":
			l := len(sc)
			if l > 0 {
				turn = sc[0]
				sc = sc[1:l]
			} else {
				fmt.Println("C")
				return
			}
		}
	}
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

func main() {
	var a, b, c string
	fmt.Scan(&a, &b, &c)

	A := strings.Split(a, "")
	B := strings.Split(b, "")
	C := strings.Split(c, "")

	ans := exec(A, B, C)
	fmt.Println(ans)
}

func exec(A, B, C []string) string {
	target := "a"
	pa, pb, pc := 0, 0, 0

	for {
		if target == "a" {
			if pa == len(A) {
				return "A"
			}
			target = A[pa]
			pa++
		} else if target == "b" {
			if pb == len(B) {
				return "B"
			}
			target = B[pb]
			pb++
		} else if target == "c" {
			if pc == len(C) {
				return "C"
			}
			target = C[pc]
			pc++
		}
	}
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

type player struct {
	name  string
	cards []string
}

func main() {
	var a, b, c string
	fmt.Scan(&a, &b, &c)

	players := []player{
		{name: "A", cards: strings.Split(a, "")},
		{name: "B", cards: strings.Split(b, "")},
		{name: "C", cards: strings.Split(c, "")},
	}
	cardPlayerIdxMap := map[string]int{"a": 0, "b": 1, "c": 2}
	curTurn := 0
	for {
		curPlayer := players[curTurn]
		if len(curPlayer.cards) == 0 {
			fmt.Println(curPlayer.name)
			return
		}
		card := curPlayer.cards[0]
		curPlayer.cards = curPlayer.cards[1:]
		curTurn = cardPlayerIdxMap[card]
	}
}
//  [go]
package main

import "fmt"

func main() {
	// Code for B - Card Game for Three (ABC Edit)
	var Sa, Sb, Sc string
	fmt.Scanf("%s\n%s\n%s", &Sa, &Sb, &Sc)

	var flag string = string('a')
	for {
		if flag == string('a') {
			flag = Sa[len(Sa)-1 : len(Sa)]
			Sa = Sa[0 : len(Sa)-1]
			if len(Sa) == 0 {
				fmt.Println("A")
				break
			}
		} else if flag == string('b') {
			flag = Sb[len(Sb)-1 : len(Sb)]
			Sb = Sb[0 : len(Sb)-1]
			if len(Sb) == 0 {
				fmt.Println("B")
				break
			}
		} else {
			flag = Sc[len(Sc)-1 : len(Sc)]
			Sc = Sc[0 : len(Sc)-1]
			if len(Sc) == 0 {
				fmt.Println("C")
				break
			}
		}
	}
}
//  [ruby]
a = gets.chomp.split("")
b = gets.chomp.split("")
c = gets.chomp.split("")

turn = "a"
loop do
    next_turn = nil
    case turn
    when "a" then
        next_turn = a.shift
    when "b" then
        next_turn = b.shift
    when "c" then
        next_turn = c.shift
    end
    if next_turn == nil
        puts turn.upcase
        exit
    else
        turn = next_turn
    end
end
//  [ruby]
sa=gets.chomp.chars
sb=gets.chomp.chars
sc=gets.chomp.chars
h = {
    'a' => sa,
    'b' => sb,
    'c' => sc,
}

c = 'a'
loop do
    c = h[c].shift
    if h[c].empty?
        puts c.upcase
        exit 0
    end
end
//  [ruby]
sa = gets.chomp
sb = gets.chomp
sc = gets.chomp
s = [sa,sb,sc]
t = {"a"=>0, "b"=>1, "c"=>2}
turn = 0
loop do
    x = s[turn]
    if x == "" then
        puts t.key(turn).upcase
        break
    end
    next_t = t[x[0]]
    s[turn] = x[1..-1]
    turn = next_t
end
//  [ruby]
a = gets.chomp
b = gets.chomp
c = gets.chomp

player = "a"
ind_hash = {"a" => 0, "b" => 0, "c" =>0}
hand_hash = {"a" => a, "b" => b, "c" =>c}

while true
  ind = ind_hash[player]
  card = hand_hash[player][ind]
  break if card.nil?
  
  player = card
  ind_hash[card] += 1
end

puts player.upcase
//  [ruby]
# 入力部
a = gets.chomp.split('')
b = gets.chomp.split('')
c = gets.chomp.split('')
arr = [a,b,c]
# p arr[0].shift
# p arr[0][0]

turn = 0
while true
  # 抜け
  if arr[turn] == []
     break
  end
  turn = case arr[turn][0]
          when "a"
            0
          when "b"
            1
          when "c"
            2
          end
  # turn 出力===================
  # if turn == 0
  #   puts "a"
  # elsif turn == 1
  #   puts "b"
  # else
  #   puts "c"
  # end
  # ===========================
  arr[turn].shift
end
if turn == 0
    puts "A"
  elsif turn == 1
    puts "B"
  else
    puts "C"
  end
//  [ruby]
alp = ['a', 'b', 'c']
a = Array.new(3) do
    gets.split('').map do |v|
        alp.index(v)
    end
end

turn = 0
while true do
    next_turn = a[turn].shift
    if a[turn].length == 0 then
        break
    end
    turn = next_turn
end

puts alp[turn]
//  [rust]
use std::io;

fn main() {
	let mut s:Vec<Vec<char>> = Vec::new();
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let mut si = buf.trim().chars().collect::<Vec<char>>();
	let mut sj = si.clone();
	let iter = sj.iter().rev();
	let mut sa:Vec<char> = Vec::new();
	for c in iter {
		sa.push(*c);
	}
	s.push(sa);
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let mut si = buf.trim().chars().collect::<Vec<char>>();
	let mut sj = si.clone();
	let iter = sj.iter().rev();
	let mut sb:Vec<char> = Vec::new();
	for c in iter {
		sb.push(*c);
	}
	s.push(sb);
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let mut si = buf.trim().chars().collect::<Vec<char>>();
	let mut sj = si.clone();
	let iter = sj.iter().rev();
	let mut sc:Vec<char> = Vec::new();
	for c in iter {
		sc.push(*c);
	}
	s.push(sc);
	let mut n = 0;
	let mut winner = 0;
	loop {
		match s[n].pop() {
			Some(c) => {
				if c == 'a' {
					n = 0;
				}else if c == 'b' {
					n = 1;
				}else{
					n = 2;
				};
			},
			None => {
				winner = n;
				break;
			},
		}
	}
	if winner == 0 {
		println!("A");
	}else if winner == 1 {
		println!("B");
	}else{
		println!("C");
	}
}
//  [rust]
use std::io::stdin;

fn main() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let a = String::from(s.trim());
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let b = String::from(s.trim());
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let c = String::from(s.trim());
    let mut s = [a, b, c];

    let mut next = 0;
    while s[next].len() > 0 {
        next = match s[next].remove(0) {
            'a' => 0,
            'b' => 1,
            _ => 2,
        };
    }

    println!(
        "{}",
        match next {
            0 => 'A',
            1 => 'B',
            _ => 'C',
        },
    );
}
//  [rust]
use proconio::input;
use proconio::marker::{Bytes, Chars};

// use std::cmp::*;
use std::collections::HashMap;

fn main() {
    input! {
        sa:Chars,
        sb:Chars,
        sc:Chars,
    }

    let mut idx: [usize; 3] = [0, 0, 0];
    let mut map: HashMap<char, usize> = HashMap::new();
    let inputs = [sa, sb, sc];
    map.insert('a', 0);
    map.insert('b', 1);
    map.insert('c', 2);

    let mut n = 'a';
    loop {
        let i: usize = idx[map[&n]];
        let s = &inputs[map[&n]];
        if s.len() <= i {
            println!("{}", n.to_uppercase());
            return;
        }
        n = s[i];
        idx[map[&n]] += 1;
    }
}
//  [rust]
use proconio::input;

fn main() {
	input!(s: [String; 3]);

	let name = ['A', 'B', 'C'];
	//let mut s = s;
	let mut turn: usize = 0;
	let mut v = vec![vec![]; 3];
	for i in 0..3 {
		v[i] = s[i].chars().collect();
	}
	loop {
		if v[turn].len() == 0 {
			println!("{}", name[turn]);
			return;
		}
		turn = v[turn][0] as usize - 'a' as usize; 
		v[turn].remove(0);
	}
}
//  [rust]
use std::io;

fn main() {
	let mut s:Vec<Vec<char>> = Vec::new();
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let sa = buf.trim().chars().collect::<Vec<char>>();
	s.push(sa);
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let sb = buf.trim().chars().collect::<Vec<char>>();
	s.push(sb);
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let sc = buf.trim().chars().collect::<Vec<char>>();
	s.push(sc);
	let mut n = 0;
	let mut winner = 0;
	loop {
		match s[n].pop() {
			Some(c) => {
				if c == 'a' {
					n = 0;
				}else if c == 'b' {
					n = 1;
				}else{
					n = 2;
				};
			},
			None => {
				winner = n;
				break;
			},
		};
	}
	if winner == 0 {
		println!("A");
	}else if winner == 1 {
		println!("B");
	}else{
		println!("C");
	}
}
//  [swift]
import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/



/*************** メインプログラム ***************/

let S = (0..<3).map{_ in readLine()!.toArray()}
var cnt = [Int](repeating: 0, count: 3)
var player = 0
while true {
    if cnt[player] == S[player].count {
        print(["A","B","C"][player])
        break
    } else {
        cnt[player] += 1
        player = ["a":0,"b":1,"c":2][S[player][cnt[player]-1]]!
    }
}
//  [swift]
import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/



/*************** メインプログラム ***************/

let Sa = readLine()!.toArray()
let Sb = readLine()!.toArray()
let Sc = readLine()!.toArray()
var S = ["a": Sa, "b": Sb, "c": Sc]
var turn = "a"
while S["a"]!.count > 0 && S["a"]!.count > 0 && S["a"]!.count > 0 {
    let tmp = S[turn]![0]
    S[turn]!.removeAtIndex(0)
    turn = tmp
}
if S["a"]!.count == 0 {
    print("A")
}
if S["b"]!.count == 0 {
    print("B")
}
if S["c"]!.count == 0 {
    print("C")
}
//  [typescript]
"use strict";

const Main = args => {
  const input = args.trim().split("\n").map(e => e.split(""));
  let S = { a: input[0], b: input[1], c: input[2] };
  let current = 'a';
  let winner = '';

  while (true) {
    if (S[current].length === 0) {
      winner = current;
      break;
    }
    let next = S[current][0];
    S[current].shift();
    current = next;
  }
  console.log(winner.toUpperCase());
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
'use strict'
 
const main = (input) => {
  input = input.split('\n');
  const a = input[0].split('')
  const b = input[1].split('')
  const c = input[2].split('')
  
  const n = 'a'
  const s = []
  
  while(true) {
    if (n==='a') {
      s=a
    }else if (n==='b') {
      s=b
    }else{
      s=c
    }
    if(s.length==0) {
      console.log(n.toUpperCase());
      break
    }
    n=s.shift()
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
function main(input: string) {
  let [sa, sb, sc] = input.split("\n").map((str: string) => str.split(""));
  let player: string = "a";
  while (1) {
    if (player === "a") {
      if (sa.length < 1) {
        console.log("A");
        break;
      }
      player = sa.shift();
      continue;
    }
    if (player === "b") {
      if (sb.length < 1) {
        console.log("B");
        break;
      }
      player = sb.shift();
      continue;
    }
    if (player === "c") {
      if (sc.length < 1) {
        console.log("C");
        break;
      }
      player = sc.shift();
      continue;
    }
  }
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
import * as fs from "fs";
const input = fs.readFileSync("/dev/stdin", "utf-8");

const main = (input: string): void => {
  const [a, b, c] = input.split("\n").map((str) => str.split(""));
  let next: string = "";

  const term = (str: string) => {
    if (str === "a") next = a.shift() ?? "";
    else if (str === "b") next = b.shift() ?? "";
    else if (str === "c") next = c.shift() ?? "";

    if (next === "") console.log(str.toUpperCase());
    // else term(next);
  };

  term(a[0]);
};

main(input);