The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one). When the guesser is answered "4 bulls 0 cows", the game is over.Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.

The first input line contains an integer n (1 ≤ n ≤ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 ≤ i ≤ n, 0 ≤ bi, ci, bi + ci ≤ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.

If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.

import sys
lines = sys.stdin.readlines()
n = int(lines[0].strip())
query = []
for i in range(1, n+1):
    (a, b, c) = lines[i].strip().split(" ")
    query.append((a, int(b), int(c)))
def compare(i):
    digits = str(i)
    digits = "0" *(4-len(digits)) + digits
    if len(set(list(digits))) != 4: return False
    for q in query:
        (a, b, c) = q
        m, n = 0, 0
        for i in range(4):
            if a[i] == digits[i]: m += 1
        for l in a:
            if l in digits: n += 1
        n -= m
        if m != b or n != c:
            return False
    return True
res = 0
count = 0
for i in range(123, 9877):
    if compare(i): count += 1; res = i
    if count >= 2: break
if count == 0: print("Incorrect data")
elif count == 1:
    digits = str(res)
    digits = "0" *(4-len(digits)) + digits
    print(digits)
else: print("Need more data")

import sys

def tolist(i):
    listx = list()
    while i > 0:
        listx.append(i % 10)
        i //= 10
    while len(listx) < 4: listx.append(0)
    return listx[::-1]

def diff(i):
    count = [0] * 10
    for x in range(4):
        count[i % 10] += 1
        i //= 10
    for val in count:
        if val > 1: return False
    return True

n, = map(int, input().split())
works = 0
lastworks = -1
guesses = list()
for i in range(n):
    a, b, c, = map(int, input().split())
    acopy = a
    charcount = [0] * 10
    for x in range(4):
        charcount[acopy % 10] += 1
        acopy //= 10
    guesses.append((tolist(a), b, c, charcount))

for i in range(1, 10000):
    if diff(i):
        l = tolist(i)
        icopy = i
        charcount = [0] * 10
        for x in range(4):
            charcount[icopy % 10] += 1
            icopy //= 10
        count = 0
        for guess in guesses:
            bulls, cows = 0, 0
            for j in range(4):
                if l[j] == guess[0][j]: bulls += 1
            for j in range(10):
                if charcount[j] > 0 and guess[3][j] > 0: cows+=1
            cows -= bulls
            if bulls == guess[1] and cows == guess[2]:
                count += 1
        if count == n:
            works += 1
            lastworks = l
if works == 0:
    print("Incorrect data")
elif works == 1:
    print(''.join(map(str, lastworks)))
else:
    print("Need more data")

def filter(candidates, num, rp, wp):
    ans = []
    for cand in candidates:
        crp = cwp = 0
        for a, b in zip(cand, num):
            if a == b:
                crp += 1
            elif a in num:
                cwp += 1

        if crp == rp and cwp == wp:
            ans.append(cand)

    return ans

def main():
    n = int(input())
    candidates = []
    for i in range(123, 9877):
        num = str(i).zfill(4)
        if len(set(num)) == 4:
            candidates.append(num)

    for _ in range(n):
        a, b, c = input().split()
        candidates = filter(candidates, a, int(b), int(c))
        if not candidates:
            print('Incorrect data')
            return

    print(candidates[0] if len(candidates) == 1 else 'Need more data')

if __name__ == "__main__":
    main()

import sys

def solve():
    n, = rv()
    works = 0
    lastworks = -1
    guesses = list()
    for i in range(n):
        a, b, c, = rv()
        acopy = a
        charcount = [0] * 10
        for x in range(4):
            charcount[acopy % 10] += 1
            acopy //= 10
        guesses.append((tolist(a), b, c, charcount))

    for i in range(1, 10000):
        if different(i):
            l = tolist(i)
            icopy = i
            charcount = [0] * 10
            for x in range(4):
                charcount[icopy % 10] += 1
                icopy //= 10
            count = 0
            for guess in guesses:
                bulls, cows = 0, 0
                for j in range(4):
                    if l[j] == guess[0][j]: bulls += 1
                for j in range(10):
                    if charcount[j] > 0 and guess[3][j] > 0: cows+=1
                cows -= bulls

                if bulls == guess[1] and cows == guess[2]:
                    count += 1
            if count == n:
                works += 1
                lastworks = l
    if works == 0:
        print("Incorrect data")
    elif works == 1:
        print(''.join(map(str, lastworks)))
    else:
        print("Need more data")

def tolist(i):
    il = list()
    while i > 0:
        il.append(i % 10)
        i //= 10
    while len(il) < 4: il.append(0)
    return il[::-1]

def different(i):
    count = [0] * 10
    for x in range(4):
        count[i % 10] += 1
        i //= 10
    for val in count:
        if val > 1: return False
    return True

def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()

# Made By Mostafa_Khaled

#! /usr/bin/python3
import sys
import pprint

def main():
    input_list = []
    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))
        """
        # DEBUG
        if line.rstrip("\n") == "exit":
            break
        """
    possible_nums = ["{0:04}".format(i) for i in range(123, 10000)] # List of all possible 4 digit numbers as strings form "0123" to "9999"

    for i in range(int(input_list[0])):
        check_list = input_list[i + 1].split(" ")
        possible_nums = filter(possible_nums, check_list[0], check_list[1], check_list[2])
        """
        # DEBUG
        print(possible_nums)
        """
    if len(possible_nums) == 0:
        print("Incorrect data")
    elif len(possible_nums) == 1:
        print(possible_nums[0])
    else:
        print("Need more data")

def check_cow(input_num, check_num, cow):
    cow_num = 0
    union_set = set(ordered_union(list(input_num), list(check_num))) # Set of Strings
    cow_num = len((set(input_num) - union_set).intersection(set(check_num) - union_set))

    return cow_num == cow

def check_bull(input_num, check_num, bull):
    bull_num = 0
    bull_num = len(ordered_union(list(input_num), list(check_num)))

    return bull_num == bull

def filter(possible_nums, input_num, bull, cow):
    filtered_list = []

    for num in possible_nums:
        if check_cow(input_num, num, int(cow)) and check_bull(input_num, num, int(bull)) and not has_repeat(num):
            filtered_list.append(num)

    return filtered_list

def ordered_union(list1, list2):
    union_list = []

    for i in range(len(list1)):
        if list1[i] == list2[i]:
            union_list.append(list1[i])
    return union_list

def has_repeat(num):
    return len(set(num)) != len(num)

if __name__ == "__main__":
    main()

c_list=[]
p_list=[]
n = int(raw_input())
for i in range(n):
    c = [x for x in raw_input().split()]
    c_list.append(c)

for i in range(0,10000):
    test=str(i).rjust(4,'0')
    test_score=0
    for c in c_list:
        match = c[0]
        mbc = int(c[1])
        mcc = int(c[2])
        tbc = 0
        tcc = 0
        for i in range(4):
            if match[i] == test[i]:
                tbc += 1
            elif match[i] in test:
                tcc += 1
        if mbc == tbc and mcc==tcc:
            test_score+=1
    if test_score == n:
        no_dup = True
        for i in range(4):
            for j in range(4):
                if i!=j and test[i]==test[j]:
                    no_dup=False
        if no_dup:
            p_list.append(test)

if len(p_list)  == 0:
    print "Incorrect data"
elif len(p_list) == 1:
    print p_list[0]
else:
    print "Need more data"

from itertools import permutations
def ch(ww):
    global s, kb
    t=0
    for i in range(n):
        b=0
        w=list(ww)
        u=list(s[i][0])
        for j in (3,2,1,0):
            if u[j]==w[j]:
                b+=1
                del u[j]
                del w[j]
        k=len(set(u)&set(w))
        if b==int(s[i][1]) and k==int(s[i][2]): t+=1
    if t==n:
        kb=ww
        return 1
    else: return 0

n = int(raw_input())
s=[[] for i in range(n)]
for k in range(n):
    s[k] =raw_input().split()

kb=''
st=0
for i in permutations('9876543210',4):
    st+=ch(''.join(i))
    if st>1:
        print ('Need more data')
        break
else:
    if st==1: print (kb)
    else: print ('Incorrect data')

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from collections import defaultdict
from math import factorial as f
from fractions import gcd as g

l = []
ret = []
n = int (raw_input ())
for i in range (n):
    a, b, c = [i for i in raw_input ().split ()]
    l.append ((a, b, c))
for i in range (0, 10000):
    s = ("0000" + str (i)) [-4:]
    if len (set (list (s))) != 4: continue
    ok = True
    for j in l:
        a, b, c = j
        x, y = 0, 0
        for k in range (4):
            if a [k] == s [k]:
                x += 1
        for k in range (4):
            for m in range (4):
                if a [k] == s [m]:
                    y += 1
        y -= x
        b, c = int (b), int (c)
        ok &= (x == b and y == c)
    if ok: ret.append (s)
if len (ret) == 1: print ret [0]
elif len (ret) < 1: print "Incorrect data"
else: print "Need more data"

def is_sat(candi, cont):
    candi_match = cont[0]
    _bcount = int(cont[1])
    _ccount = int(cont[2])
    bcount = 0
    ccount = 0
    for i in xrange(4):
        if candi_match[i] == candi[i]:
            bcount += 1
        elif candi_match[i] in candi:
            ccount += 1
    return (_bcount == bcount and _ccount == ccount)

constraints = []

N = int(raw_input())
while N>0:
    constraints.append([x for x in raw_input().split()])
    N-=1
satisfies = []
for i in xrange(0,10000):
    candi = str(i).rjust(4,'0')
    satcount = 0
    for cont in constraints:
        if is_sat(candi, cont):
            satcount+=1
    if satcount == len(constraints):
        valid = True
        for i in xrange(4):
            for j in xrange(4):
                if i!=j:
                    if candi[i]==candi[j]:
                        valid=False
        if valid:
            satisfies.append(candi)

goo = len(satisfies)
if goo  == 1:
    print satisfies[0]
elif goo == 0:
    print "Incorrect data"
else:
    print "Need more data"

import sys
import string

def check(s1, s2):
    t1 = 0
    t2 = 0
    for i in xrange(len(s1)):
        if s1[i] == s2[i]:
            t1 += 1
        elif s1[i] in s2:
            t2 += 1
    return (t1, t2)

guesses = []
for i in ['%0*d' % (4, i) for i in xrange(10000)]:
    t = []
    for j in i:
        if not j in t:
            t.append(j)
        else:
            break
    else:
        guesses.append(i)

lines = []
for i in sys.stdin.readlines()[1:]:
    line = i.rstrip().split(" ")
    lines.append((line[0], int(line[1]), int(line[2])))

c = 0
ans = None
for g in guesses:
    for i in lines:
        s1 = i[0]
        t1 = i[1]
        t2 = i[2]
        if (t1, t2) != check(s1, g):
            break
    else:
        c += 1
        ans = g

if c == 0:
    print "Incorrect data"
else:
    if c != 1:
        print "Need more data"
    else:
        print ans

n = input()
d = {}
a = []

def digits (n):
    rs = []
    p2 = 0
    for i in range(4):
        rs.append(n%10)
        n/=10
    return set(rs),rs

for i in range(10000):
    l,ll = digits(i)
    if len(l)<4: continue
    a.append(i)
    d[i]=(l,ll)

def oc(k,x,b,c):
    kl,kll=d[k]
    xl,xll=d[x]
    nb = sum(int(x==y) for x,y in zip(kll,xll))
    if nb!=b: return False
    nc = sum(int(x in kl) for x in xl)-nb
    return nc==c

for i in range(n):
    k,b,c = map(int,raw_input().split())
    a = filter(lambda x:oc(k,x,b,c),a)

if not a: print "Incorrect data"
elif len(a)==1: print "%04d"%a[0]
else: print "Need more data"

def findBulls(a, b):
  total = 0
  for i in range(len(a)):
    if a[i] == b[i]:
      total += 1

  return total

def findCows(a, b):

  l1 = []
  l2 = []

  for i in range(len(a)):
    l1.append(int(a[i]))
    l2.append(int(b[i]))

  s1 = set(l1)
  s2 = set(l2)

  return (len(s1.intersection(s2))) - findBulls(a, b)

tps = []
matches = []

#print findBulls('0012', '1234')
#print findCows('0012', '1234')

total = int(raw_input())

for i in range(total):
  l = raw_input()
  parts = l.split()
  g = parts[0]
  b = int(parts[1])
  c = int(parts[2])

  tps.append((g, b,c ))

def findMatches(i, j, k, l, tps):
  first = i
  second = j
  third = k
  fourth = l

  allMatched = True

  for t in tps:
    if (findBulls(str(i) + str(j) + str(k) + str(l), t[0]) == t[1]) and (findCows(str(i) + str(j) + str(k) + str(l), t[0]) == t[2]):
      pass
    else:
      allMatched = False

  if allMatched:
    matches.append(str(i) + str(j) + str(k) + str(l))

for i in range(10):
  for j in range(10):
    for k in range(10):
      for l in range(10):
        st = set()
        st.add(i)
        st.add(j)
        st.add(k)
        st.add(l)
        if len(st) == 4:
          findMatches(i, j, k, l, tps)

if len(matches) == 1:
  print matches[0]
elif len(matches) == 0:
  print "Incorrect data"
else:
  print "Need more data"

# -*- coding: utf-8 -*-
from itertools import combinations, permutations

nums = set(map(str, range(10)))

def query(x, y):
    b = set([ i for i in range(len(x)) if x[i] == y[i]])
    r = set(x)&set(y)
    for i in b: r.remove(x[i])
    return len(b), len(r)

mother = set()
for p in permutations(nums, 4):
    mother.add(p)

n = input()
clue = [raw_input().split() for _ in range(n)]

for cl in clue:
    expr, bull, cow = cl[0], int(cl[1]), int(cl[2])
    rm = set()
    for cand in mother:
        b, c = query(cand, tuple(expr))
        if b != bull or c != cow:
            rm.add(cand)
    mother ^= rm

status = len(mother)
if status == 0:
    print 'Incorrect data'
elif status == 1:
    print ''.join(tuple(mother)[0])
else:
    print 'Need more data'

import sys

def check(s1, s2):
	a = 0
	n = len(s1)
	for i in range(0,n):
		a += (s1[i]==s2[i])
	b = len(set(s1) & set(s2)) - a
	return (a,b)

def ch(s):
	return len(set(s)) == 4

n = int(raw_input())

pr = []
ok = []

for i in range(0,10000):
	s = str(i)
	if i < 1000:
		s = '0'+s
	if ch(s)==True:
		pr.append(s)
		ok.append(True)

for i in range(0,n):
	l = raw_input().split()

	s = l[0]
	(a,b) = map(int,l[1:])

	for j in range(0,len(pr)):
		if ok[j]==False:
			continue
		if check(pr[j], s) != (a,b):
			ok[j] = False

sm = len(filter(lambda x:x, ok))
if sm == 0:
	print "Incorrect data"
else:
	if sm == 1:
		for i in range(0,len(ok)):
			if ok[i]==True:
				print pr[i]
				break
	else:
		print "Need more data"

import string
import itertools
import sys

def bullcow(num1, num2):
    num1 = list(num1)
    num2 = list(num2)
    bull = 0
    cow = 0
    for idx1, dg1 in enumerate(num1):
        for idx2, dg2 in enumerate(num2):
            if dg2 == dg1:
                if idx2 == idx1:
                    bull += 1
                else:
                    cow += 1
    return bull, cow

n = int(raw_input())
guesses = []
bullscow = []
for _ in range(n):
    g, b, c = raw_input().split()
    guesses.append(g)
    bullscow.append((int(b), int(c)))

candidates = set(itertools.permutations(string.digits, r=4))

for i, guess in enumerate(guesses):
    new_candidates = set()
    b, c = bullscow[i]
    for s in candidates:
        b2, c2 = bullcow(s, guess)
        if b2==b and c2==c:
            new_candidates.add(s)
    candidates = new_candidates
    if len(candidates) == 0:
        print 'Incorrect data'
        sys.exit(0)

if len(candidates)>1:
    print 'Need more data'
    sys.exit(0)

print ''.join(candidates.pop())

import itertools

n = input()
quiz = ''
answers = 0
data = []

for i in xrange(0, n):
  data.append(raw_input().split())

def check(hyp):
  for num, bull, cow in data:
    uknow = len(set(hyp) & set(num))
    know = len([i for i, j in zip(num, hyp) if i == j])
    if uknow-know != int(cow) or know != int(bull):
      return 0
  return 1

for hyp in itertools.permutations('0123456789', 4):
  if (check(''.join(hyp))):
    quiz = ''.join(hyp)
    answers = answers + 1

if answers == 0:
  print "Incorrect data"
if answers == 1:
  print quiz
if answers > 1:
  print "Need more data"

#In the name of ALLAH
def getBC(a, guess):
    b = 0
    a1 = g1 = ""
    for i in range(4):
        if a[i] == guess[i]:
            b += 1
        else:
            a1 += a[i]
            g1 += guess[i]
    c = 0
    for i in a1:
        if i in g1:
            c += 1
    return str(b), str(c)

n = int(raw_input())
k = []
pos = None
ok = True
for i in range(n):
    k.append(raw_input().split())
for i in range(0, 9999):
    a = str(i).zfill(4)
    if len(set(a)) == 4:
        ok = True
        for j in range(n):
            b, c = getBC(a, k[j][0])
            if b != k[j][1] or c != k[j][2]:
                ok = False
        if ok == True:
            if pos is None:
                pos = a
            else:
                print "Need more data"
                exit(0)

if pos is None:
    print "Incorrect data"
else:
    print pos

import math, time, re

ln = lambda : raw_input()
cnv = lambda s: map(int, s.split())
rInt = lambda s: int(s)
rFloat = lambda s: float(s)
rLong = lambda s: long(s)
rLine = lambda f: f.readline()

b = [True for i in xrange(0, 10)]

llong = []
def per(s):
    if len (s) == 4:
        llong.append(s)
        return
    else:
        for i in xrange(0, 10):
            if b[i]:
                b[i] = False
                per(s + str(i))
                b[i] = True

def check(s1, s2):
    return (len([i for i in xrange(0, 4) if (s1[i] in s2 and s1[i] == s2[i])])), \
(len([i for i in xrange(0, 4) if (s1[i] in s2 and s1[i] != s2[i])]))

start = time.time()
k, t = 0, 0
n = int(raw_input())
l = []
per("")
#print llong
for i in xrange(0,n):
    l.append(ln().split())
for i in xrange(0, len(llong)):
    b = True
    for j in xrange(0, n):
        if (check(llong[i], l[j][0]) != (int(l[j][1]), int(l[j][2]))):
            b = False
            break
    if b:
        k += 1
        t = llong[i]
    if k > 1:
        break
#print l[0][0]
#print l[0][1]
#print l[0][2]
#print llong[0]
if k > 1:
    print 'Need more data'
elif k == 1:
    print t
else:
    print 'Incorrect data'
#per(s)
#print llong
#print check (s1, s2)
#print 'Time exceeded:', time.time() - start

from itertools import *

n = input ()
data = map (lambda a: (a[0], int (a[1]), int (a[2])), [raw_input ().split () for i in xrange (n)])

def valid (s):
    for a, b, c in data:
        x, y = len (set (s) & set (a)), len ([i for i, j in zip (a, s) if i == j])
        if x - y != c or y != b:
            return 0
    return 1

ans, cnt = '', 0
for s in permutations ('0123456789', 4):
    if valid (''.join (s)):
        ans = s
        cnt += 1

print ''.join (ans) if cnt == 1 else 'Need more data' if cnt > 1 else 'Incorrect data'

a = [(x[0], int(x[1]), int(x[2])) for x in [raw_input().split() for i in xrange(input())]]
ans = []
def cal(x, y):
    a, b = 0, 0
    for i in xrange(4):
        if x[i] == y[i]: a += 1
        else:
            for j in xrange(4):
                if i != j and x[i] == y[j]:
                    b += 1
                    break
    return (a, b)
def check(x):
    bit = ''
    while x:
        bit += chr(ord('0') + x % 10)
        x /= 10
    while len(bit) != 4: bit += '0'
    if len(set(bit)) != 4: return
    for item in a:
        if cal(item[0], bit[::-1]) != (item[1], item[2]): return
    ans.append(bit[::-1])
for i in xrange(1, 10000):
    check(i)
if not ans: print 'Incorrect data'
elif len(ans) > 1: print 'Need more data'
else: print ans[0]

from itertools import *

n = int(raw_input())
a = map(lambda t: (t[0], int(t[1]), int(t[2])), [raw_input().split() for _ in xrange(n)])

def check(s):
    for u,v,w in a:
        x, y = len( set(s)&set(u) ), 0
        for i in xrange(4):
            if s[i]==u[i]:
                y += 1
        if x-y!=w or y!=v:
            return 0
    return 1

ans, cnt = "", 0
for s in permutations("0123456789", 4):
    if check("".join(s)):
        ans = "".join(s)
        cnt += 1
if cnt == 1:
    print ans
elif cnt == 0:
    print "Incorrect data"
else:
    print "Need more data"

def getStr(x):
	ans = []
	while x > 0:
		ans.append(x % 10)
		x /= 10
	ans += [0] * (4 - len(ans))
	return "".join(map(str, ans))[::-1]

def main():
	n = input()
	data = []
	for i in xrange(n):
		d, b, c = map(str, raw_input().split())
		data.append((d, int(b), int(c)))
	ans = ""
	for i in xrange(0, 10000):
		s = getStr(i)
		if s.count(s[0]) > 1 or s.count(s[1]) > 1 or s.count(s[2]) > 1 or s.count(s[3]) > 1: continue
		isOk = True
		for j in xrange(n):
			b, c = 0, 0
			for k in xrange(4):
				if data[j][0][k] == s[k]: b += 1
				elif s[k] in data[j][0]: c += 1
			if b != data[j][1] or c != data[j][2]:
				isOk = False
				break
		if isOk:
			if ans != "":
				print "Need more data"
				return
			ans = s
	print ans if ans != "" else "Incorrect data"

if __name__ == "__main__": main()

d1 = [0,0,0,0]
d2 = [0,0,0,0]

def digits (num,d):
	aux = num
	for i in range(0,4):
		d[i] = num%10
		num /= 10
	if aux < 1000:
		d[3] = 0

def bc (num1,num2):
	b,c = 0,0
	digits(num1,d1)
	digits(num2,d2)

	for i in range(0,4):
		for j in range(0,4):
			if i == j and d1[i] == d2[j]: b+=1
			if i != j and d1[i] == d2[j]: c+=1

	return (b,c)

v = [] ; usei = [0]*10

def preenche(index,num):
	if index == 4:
		v.append(num)
	else:
		for i in range(0,10):
			if usei[i] == 0:
				usei[i] = 1
				preenche(index+1,num*10+i)
				usei[i] = 0

preenche(0,0)
check = [1]*len(v)

n =  input() ; s = 0;
for i in range(0,n):
	linha = map(int,raw_input().strip().split())
	guess = (linha[1],linha[2])
	for i in range(0,len(v)):
		res = bc(linha[0],v[i])
		if res != guess: check[i] = 0

for i in range(0,len(v)):
	if check[i] == 1:
		s += 1; res = v[i]

if s == 0: print 'Incorrect data'
if s == 1:
	if res < 1000: print '0'+str(res)
	else: print res
if s > 1: print 'Need more data'

from sys import stdin

rstrs = lambda: [str(x) for x in stdin.readline().split()]
strs_inp = lambda n: [rstrs() for _ in range(n)]
n = int(input())
qur, sol = strs_inp(n), []

for i in range(123, 9877):
    num = '0' * (4 - len(str(i))) + str(i)
    if len(set(num)) != 4:
        continue

    q = 0
    for a, b, c in qur:
        same, diff = 0, 0
        for j in range(4):
            if num[j] == a[j]:
                same += 1
            if a[j] in num:
                diff += 1

        diff -= same
        if diff == int(c) and same == int(b):
            q += 1

    if q == n:
        sol.append(num)

if len(sol) > 1:
    print('Need more data')
elif not len(sol):
    print('Incorrect data')
else:
    print(sol[0])

import sys
from array import array  # noqa: F401
from itertools import product

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

n = int(input())
cand = set()

for i, (a, b, c) in enumerate(input().split() for _ in range(n)):
    a = list(map(int, a))
    b, c = int(b), int(c)
    s = set()

    for p in product(range(10), repeat=4):
        if len(set(p)) < 4:
            continue
        b_, c_ = 0, 0
        for j in range(4):
            if p[j] == a[j]:
                b_ += 1
            elif p[j] in a:
                c_ += 1
        if b == b_ and c == c_:
            s.add(''.join(map(str, p)))

    if i == 0:
        cand = s
    else:
        cand &= s

if len(cand) == 1:
    print(cand.pop())
elif len(cand) > 1:
    print('Need more data')
elif not cand:
    print('Incorrect data')
else:
    assert False

n=int(input())
array=[str(t).zfill(4) for t in range(10000) if len(set(str(t).zfill(4)))==4]
# print (array)
for _ in range(n):
    a,b,c=input().split()
    b=int(b)
    c=int(c)
    # for u in array:
        # print (u, set(u).intersection(set(a)))
    array=[u for u in array if len(set(u).intersection(set(a)))==b+c and sum(u[i]==a[i] for i in range(4))==b]
    # print (array)
if len(array)>1:print("Need more data")
elif len(array)==1:print(array[0])
else:print("Incorrect data")

#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

numbers=set()
for i in range(10):
    for j in range(10):
        for k in range(10):
            for l in range(10):
                if(i!=j and i!=k and i!=l and j!=k and j!=l and k!=l):
                    numbers.add(str(i)+str(j)+str(k)+str(l))

def count():
    possible=set()

    for num in numbers:
        cow=0
        bulls=0

        for i in range(4):
            for j in range(4):
                if(num[i]==n[j]):
                        bulls+=1
                        break
            if(num[i]==n[i]): cow+=1

        if(cow==x and bulls-cow==y):
            possible.add(num)

    return possible

for _ in range(Int()):
    n,x,y=input().split()
    x=int(x)
    y=int(y)

    numbers=count()
    # print(numbers)

if(len(numbers)==1): print(list(numbers)[0])
elif(len(numbers)>1): print('Need more data')
else: print('Incorrect data')

'''input
8
7954 0 1
5638 0 1
8204 0 2
8293 1 1
3598 0 1
0894 0 1
6324 1 2
0572 0 1
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy

setrecursionlimit(15000)

def take_intersection():
	pass

def discover_digits(guess):
	myset = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
	flag = 0
	count = 0
	final = []
	comb = permutations(myset, 4)
	for i in comb:
		ans = get_answer(guess, list(i))
		if len(ans) == 4:
			count += 1
			final.append(ans)
			flag = 1

	if count == 1:
		for i in final[0]:
			print(i, end = '')
	elif count > 1:
		print("Need more data")
	if flag == 0:
		print("Incorrect data")

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, answer):
	flag = 0
	ans = []
	for j in range(len(guess)):
		num = guess[j][0]
		if check(answer, guess, j):
			pass
		else:
			break
	else:
		ans = answer

	return ans

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# getting ready final list
final = []
base = set()
discover_digits(guess)

import sys

def solve():
    n, = rv()
    works = 0
    lastworks = -1
    guesses = list()
    for i in range(n):
        a, b, c, = rv()
        acopy = a
        charcount = [0] * 10
        for x in range(4):
            charcount[acopy % 10] += 1
            acopy //= 10
        guesses.append((tolist(a), b, c, charcount))

    for i in range(1, 10000):
        if different(i):
            l = tolist(i)
            icopy = i
            charcount = [0] * 10
            for x in range(4):
                charcount[icopy % 10] += 1
                icopy //= 10
            count = 0
            for guess in guesses:
                bulls, cows = 0, 0
                for j in range(4):
                    if l[j] == guess[0][j]: bulls += 1
                for j in range(10):
                    if charcount[j] > 0 and guess[3][j] > 0: cows+=1
                cows -= bulls

                if bulls == guess[1] and cows == guess[2]:
                    count += 1
            if count == n:
                works += 1
                lastworks = i
    if works == 0:
        print("Incorrect data")
    elif works == 1:
        print(lastworks)
    else:
        print("Need more data")

def tolist(i):
    il = list()
    while i > 0:
        il.append(i % 10)
        i //= 10
    while len(il) < 4: il.append(0)
    return il[::-1]

def different(i):
    count = [0] * 10
    for x in range(4):
        count[i % 10] += 1
        i //= 10
    for val in count:
        if val > 1: return False
    return True

def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()

#! /usr/bin/python3
import sys

def main():
    input_list = []
    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    possible_nums = ["{0:04}".format(i) for i in range(123, 10000)] # List of all possible 4 digit numbers as strings form "0123" to "9999"

    for i in range(int(input_list[0])):
        check_list = input_list[i + 1].split(" ")
        possible_nums = filter(possible_nums, int(check_list[0]), int(check_list[1]), int(check_list[2]))

    if len(possible_nums) == 0:
        print("Incorrect data")
    elif len(possible_nums) == 1:
        print(possible_nums[0])
    else:
        print("Need more data")

def check_cow(input_num, check_num, cow):
    cow_num = 0
    union_set = set(ordered_union(list(str(input_num)), list(str(check_num)))) # Set of Strings
    cow_num = len((set(str(input_num)) - union_set).intersection((set(str(check_num)) - union_set)))

    return cow_num == cow

def check_bull(input_num, check_num, bull):
    bull_num = 0
    bull_num = len(ordered_union(list(str(input_num)), list(str(check_num))))

    return bull_num == bull

def filter(possible_nums, input_num, bull, cow):
    filtered_list = []

    for num in possible_nums:
        if check_cow(input_num, num, cow) and check_bull(input_num, num, bull):
            filtered_list.append(num)

    return filtered_list

def ordered_union(list1, list2):
    union_list = []

    for i in range(len(list1)):
        if list1[i] == list2[i]:
            union_list.append(list1[i])
    return union_list

if __name__ == "__main__":
    main()

#! /usr/bin/python3
import sys
import pprint

def main():
    input_list = []
    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    possible_nums = ["{0:04}".format(i) for i in range(123, 10000)] # List of all possible 4 digit numbers as strings form "0123" to "9999"

    for i in range(int(input_list[0])):
        check_list = input_list[i + 1].split(" ")
        possible_nums = filter(possible_nums, int(check_list[0]), int(check_list[1]), int(check_list[2]))

    if len(possible_nums) == 0:
        print("Incorrect data")
    elif len(possible_nums) == 1:
        print(possible_nums[0])
    else:
        print("Need more data")

def check_cow(input_num, check_num, cow):
    cow_num = 0
    union_set = set(ordered_union(list(str(input_num)), list(str(check_num)))) # Set of Strings
    cow_num = len((set(str(input_num)) - union_set).intersection((set(str(check_num)) - union_set)))

    return cow_num == cow

def check_bull(input_num, check_num, bull):
    bull_num = 0
    bull_num = len(ordered_union(list(str(input_num)), list(str(check_num))))

    return bull_num == bull

def filter(possible_nums, input_num, bull, cow):
    filtered_list = []

    for num in possible_nums:
        if check_cow(input_num, num, cow) and check_bull(input_num, num, bull) and not has_repeat(num):
            filtered_list.append(num)

    return filtered_list

def ordered_union(list1, list2):
    union_list = []

    for i in range(len(list1)):
        if list1[i] == list2[i]:
            union_list.append(list1[i])
    return union_list

def has_repeat(num):
    return len(set(num)) != len(num)

if __name__ == "__main__":
    main()

def is_sat(candi, cont):
    candi_match = cont[0]
    _bcount = int(cont[1])
    _ccount = int(cont[2])
    bcount = 0
    ccount = 0
    for i in xrange(4):
        if candi_match[i] == candi[i]:
            bcount += 1
        elif candi_match[i] in candi:
            ccount += 1
    return (_bcount == bcount and _ccount == ccount)

constraints = []

N = int(raw_input())
while N>0:
    constraints.append([x for x in raw_input().split()])
    N-=1
satisfies = []
for i in xrange(0,10000):
    candi = str(i).rjust(4,'0')
    satcount = 0
    for cont in constraints:
        if is_sat(candi, cont):
            satcount+=1
    if satcount == len(constraints):
        satisfies.append(candi)

goo = len(satisfies)
if goo  == 1:
    print satisfies[0]
elif goo == 0:
    print "Incorrect data"
else:
    print "Need more data"

def is_sat(candi, cont):
    candi_match = cont[0]
    _bcount = int(cont[1])
    _ccount = int(cont[2])
    bcount = 0
    ccount = 0
    for i in xrange(4):
        if candi_match[i] == candi[i]:
            bcount += 1
        elif candi_match[i] in candi:
            ccount += 1
    return (_bcount == bcount and _ccount == ccount)

constraints = []

N = int(raw_input())
while N>0:
    constraints.append([x for x in raw_input().split()])
    N-=1
satisfies = []
for i in xrange(0,10000):
    candi = str(i).rjust(4,'0')
    satcount = 0
    for cont in constraints:
        if is_sat(candi, cont):
            satcount+=1
    if satcount == len(constraints):
        satisfies.append(candi)

goo = len(satisfies)
if goo  == 1:
    valid = True
    for i in xrange(4):
        for j in xrange(4):
            if i!=j:
                if satisfies[0][i]==satisfies[0][j]:
                    valid=False
    if valid:
        print satisfies[0]
    else:
        print "Need more data"
elif goo == 0:
    print "Incorrect data"
else:
    print "Need more data"

def is_sat(candi, cont):
    candi_match = cont[0]
    _bcount = int(cont[1])
    _ccount = int(cont[2])
    bcount = 0
    ccount = 0
    for i in xrange(4):
        if candi_match[i] == candi[i]:
            bcount += 1
        elif candi_match[i] in candi:
            ccount += 1
    return (_bcount == bcount and _ccount == ccount)

constraints = []

N = int(raw_input())
while N>0:
    constraints.append([x for x in raw_input().split()])
    N-=1
satisfies = []
for i in xrange(0,10000):
    candi = str(i).rjust(4,'0')
    satcount = 0
    for cont in constraints:
        if is_sat(candi, cont):
            satcount+=1
    if satcount == len(constraints):
        satisfies.append(candi)

goo = len(satisfies)
if goo  == 1:
    valid = True
    for i in xrange(4):
        for j in xrange(4):
            if i!=j:
                if satisfies[0][i]==satisfies[0][j]:
                    valid=False
    if valid:
        print satisfies[0]
    else:
        print "Incorrect data"
elif goo == 0:
    print "Incorrect data"
else:
    print "Need more data"

def findBulls(a, b):
  total = 0
  for i in range(len(a)):
    if a[i] == b[i]:
      total += 1

  return total

def findCows(a, b):

  l1 = []
  l2 = []

  for i in range(len(a)):
    l1.append(int(a[i]))
    l2.append(int(b[i]))

  s1 = set(l1)
  s2 = set(l2)

  return (len(s1.intersection(s2))) - findBulls(a, b)

tps = []
matches = []

#print findBulls('0012', '1234')
#print findCows('0012', '1234')

total = int(raw_input())

for i in range(total):
  l = raw_input()
  parts = l.split()
  g = parts[0]
  b = int(parts[1])
  c = int(parts[2])

  tps.append((g, b,c ))

def findMatches(i, j, k, l, tps):
  first = i
  second = j
  third = k
  fourth = l

  allMatched = True

  for t in tps:
    if (findBulls(str(i) + str(j) + str(k) + str(l), t[0]) == t[1]) and (findCows(str(i) + str(j) + str(k) + str(l), t[0]) == t[2]):
      pass
    else:
      allMatched = False

  if allMatched:
    matches.append(str(i) + str(j) + str(k) + str(l))

for i in range(10):
  for j in range(10):
    for k in range(10):
      for l in range(10):
        findMatches(i, j, k, l, tps)

if len(matches) == 1:
  print matches[0]
elif len(matches) == 0:
  print "Incorrect data"
else:
  print "Need more data"

def check(s1, s2):
	a = 0
	n = len(s1)
	for i in range(0,n):
		a += (s1[i]==s2[i])
	b = len(set(s1) & set(s2)) - a
	return (a,b)

n = int(raw_input())

pr = []
ok = []

for i in range(0,10000):
	s = str(i)
	if s < 1000:
		s = '0'+s
	if len(set(s)) == 4:
		pr.append(s)
		ok.append(True)

for i in range(0,n):
	l = raw_input().split()

	s = l[0]
	(a,b) = map(int,l[1:])

	for j in range(0,len(pr)):
		if ok[j]==False:
			continue
		if check(pr[j], s) != (a,b):
			ok[j] = False

sm = len(filter(lambda x:x, ok))
if sm == 0:
	print "Incorrect data"
else:
	if sm == 1:
		for i in range(0,len(ok)):
			if ok[i]==True:
				print pr[i]
				break
	else:
		print "Need more data"

import sys

def check(s1, s2):
	a = 0
	n = len(s1)
	for i in range(0,n):
		a += (s1[i]==s2[i])
	b = len(set(s1) & set(s2)) - a
	return (a,b)

def ch(s):
	return len(set(s)) == 4

n = int(raw_input())

pr = []
ok = []

for i in range(0,10000):
	s = str(i)
	if s < 1000:
		s = '0'+s
	if ch(s)==True:
		pr.append(s)
		ok.append(True)

for i in range(0,n):
	l = raw_input().split()

	s = l[0]
	(a,b) = map(int,l[1:])

	if ch(s)==False:
		print "Incorrect data"
		sys.exit()

	for j in range(0,len(pr)):
		if ok[j]==False:
			continue
		if check(pr[j], s) != (a,b):
			ok[j] = False

sm = len(filter(lambda x:x, ok))
if sm == 0:
	print "Incorrect data"
else:
	if sm == 1:
		for i in range(0,len(ok)):
			if ok[i]==True:
				print pr[i]
				break
	else:
		print "Need more data"

import string
import itertools
import sys

def bullcow(num1, num2):
    num1 = list(num1)
    num2 = list(num2)
    bull = 0
    cow = 0
    for idx1, dg1 in enumerate(num1):
        for idx2, dg2 in enumerate(num2):
            if dg2 == dg1:
                if idx2 == idx1:
                    bull += 1
                else:
                    cow += 1
    return bull, cow

n = int(raw_input())
guesses = []
bullscow = []
for _ in range(n):
    g, b, c = raw_input().split()
    guesses.append(g)
    bullscow.append((int(b), int(c)))

candidates = set(itertools.product(string.digits, repeat=4))

for i, guess in enumerate(guesses):
    new_candidates = set()
    b, c = bullscow[i]
    for s in candidates:
        b2, c2 = bullcow(s, guess)
        if b2==b and c2==c:
            new_candidates.add(s)
    candidates = new_candidates
    if len(candidates) == 0:
        print 'Incorrect data'
        sys.exit(0)

if len(candidates)>1:
    print 'Need more data'
    sys.exit(0)

print ''.join(candidates.pop())

import string
import itertools
import sys

def bullcow(num1, num2):
    num1 = list(num1)
    num2 = list(num2)
    bull = 0
    cow = 0
    for idx1, dg1 in enumerate(num1):
        for idx2, dg2 in enumerate(num2):
            if dg2 == dg1:
                if idx2 == idx1:
                    bull += 1
                else:
                    cow += 1
    return bull, cow

n = int(raw_input())
guesses = []
bullscow = []
for _ in range(n):
    g, b, c = raw_input().split()
    guesses.append(g)
    bullscow.append((int(b), int(c)))

candidates = set(itertools.permutations(string.digits, r=4))

for i, guess in enumerate(guesses):
    new_candidates = set()
    b, c = bullscow[i]
    for s in candidates:
        b2, c2 = bullcow(s, guess)
        if b2==b and c2==c:
            new_candidates.add(s)
    candidates = new_candidates
    if len(candidates) == 0:
        print 'Incorrect data'
        sys.exit(0)

for c in candidates:
    print c

if len(candidates)>1:
    print 'Need more data'
    sys.exit(0)

print ''.join(candidates.pop())

import itertools

n = input()
quiz = ''
answers = 0
data = []

for i in xrange(0, n):
  data.append(raw_input().split())

def check(hyp):
  for num, bull, cow in data:
    uknow = len(set(hyp) & set(num))
    know = len([i for i, j in zip(num, hyp) if i == j])
    if uknow-know != int(cow) or know != int(bull):
      return 0
  return 1

for hyp in itertools.permutations('0123456789', 4):
  if (check(''.join(hyp))):
    print ''.join(hyp)
    quiz = ''.join(hyp)
    answers = answers + 1

if answers == 0:
  print "Incorrect data"
if answers == 1:
  print quiz
if answers > 1:
  print "Need more data"

a = [(x[0], int(x[1]), int(x[2])) for x in [raw_input().split() for i in xrange(input())]]
def cal(x, y):
    a, b = 0, 0
    for i in xrange(4):
        if x[i] == y[i]: a += 1
        else:
            for j in xrange(4):
                if i != j and x[i] == y[j]:
                    b += 1
                    break
    return (a, b)
def check(x):
    bit = ''
    while x:
        bit += chr(ord('0') + x % 10)
        x /= 10
    while len(bit) != 4: bit += '0'
    for item in a:
        if cal(item[0], bit[::-1]) != (item[1], item[2]): return False
    return True
ans = filter(check, range(1, 10000))
if not ans: print 'Incorrect data'
elif len(ans) > 1: print 'Need more data'
else: print ans[0]

a = [(x[0], int(x[1]), int(x[2])) for x in [raw_input().split() for i in xrange(input())]]
def cal(x, y):
    a, b = 0, 0
    for i in xrange(4):
        if x[i] == y[i]: a += 1
        else:
            for j in xrange(4):
                if i != j and x[i] == y[j]:
                    b += 1
                    break
    return (a, b)
def check(x):
    bit = ''
    while x:
        bit += chr(ord('0') + x % 10)
        x /= 10
    while len(bit) != 4: bit += '0'
    if len(set(bit)) != 4: return False
    for item in a:
        if cal(item[0], bit[::-1]) != (item[1], item[2]): return False
    return True
ans = filter(check, range(1, 10000))
if not ans: print 'Incorrect data'
elif len(ans) > 1: print 'Need more data'
else: print ans[0]

a = [(x[0], int(x[1]), int(x[2])) for x in [raw_input().split() for i in xrange(input())]]
ans = []
def cal(x, y):
    a, b = 0, 0
    for i in xrange(4):
        if x[i] == y[i]: a += 1
        else:
            for j in xrange(4):
                if i != j and x[i] == y[j]:
                    b += 1
                    break
    return (a, b)
def check(x):
    bit = ''
    while x:
        bit += chr(ord('0') + x % 10)
        x /= 10
    while len(bit) != 4: bit += '0'
    if len(set(bit)) != 4: return
    for item in a:
        if cal(item[0], bit[::-1]) != (item[1], item[2]): return
    ans.append(bit)
for i in xrange(1, 10000):
    check(i)
if not ans: print 'Incorrect data'
elif len(ans) > 1: print 'Need more data'
else: print ans[0]

from itertools import *

n = int(raw_input())
a = [map(int, raw_input().split()) for _ in xrange(n)]

def check(s):
    for u,v,w in a:
        u = str(u)
        x, y = len( set(s)&set(u) ), 0
        for i in xrange(4):
            if s[i]==u[i]:
                y += 1
        if x-y!=w or y!=v:
            return 0
    return 1

ans, cnt = "", 0
for s in permutations("0123456789", 4):
    if check(s):
        ans = s
        cnt += 1
if cnt == 1:
    print s
elif cnt == 0:
    print "Incorrect data"
else:
    print "Need more data"

d1 = [0,0,0,0]
d2 = [0,0,0,0]

def digits (num,d):
	aux = num
	for i in range(0,4):
		d[i] = num%10
		num /= 10
	if aux < 1000:
		d[3] = 0

def bc (num1,num2):
	b,c = 0,0
	digits(num1,d1)
	digits(num2,d2)

	for i in range(0,4):
		for j in range(0,4):
			if i == j and d1[i] == d2[j]: b+=1
			if i != j and d1[i] == d2[j]: c+=1

	return (b,c)

v = [] ; usei = [0]*10

def preenche(index,num):
	if index == 4:
		v.append(num)
	else:
		for i in range(0,10):
			if usei[i] == 0:
				usei[i] = 1
				preenche(index+1,num*10+i)
				usei[i] = 0

preenche(0,0)
check = [1]*len(v)

n =  input() ; s = 0;
for i in range(0,n):
	linha = map(int,raw_input().strip().split())
	guess = (linha[1],linha[2])
	for i in range(0,len(v)):
		res = bc(linha[0],v[i])
		if res != guess: check[i] = 0

for i in range(0,len(v)):
	if check[i] == 1:
		s += 1; res = v[i]

if s == 0: print 'Incorrect data'
if s == 1: print res
if s > 1: print 'Need more data'

n=int(input())
array=[str(t).zfill(4) for t in range(10000) if len(set(str(t).zfill(4)))==4]
print (array)
for _ in range(n):
    a,b,c=input().split()
    b=int(b)
    c=int(c)
    # for u in array:
        # print (u, set(u).intersection(set(a)))
    array=[u for u in array if len(set(u).intersection(set(a)))==b+c and sum(u[i]==a[i] for i in range(4))==b]
    # print (array)
if len(array)>1:print("Need more data")
elif len(array)==1:print(array[0])
else:print("Incorrect data")

#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

numbers=set()
for i in range(10):
    for j in range(10):
        for k in range(10):
            for l in range(10):
                if(i!=j and j!=k and k!=l):
                    numbers.add(str(i)+str(j)+str(k)+str(l))

def count():
    possible=set()

    for num in numbers:
        cow=0
        bulls=0
        for i in range(4):
            for j in range(4):
                if(num[i]==n[j]):
                    if(i!=j): bulls+=1
                    else: cow+=1
        if(cow==x and bulls==y):
            possible.add(num)

    return possible

for _ in range(Int()):
    n,x,y=input().split()
    x=int(x)
    y=int(y)

    numbers=count()

if(len(numbers)==1): print(list(numbers)[0])
elif(len(numbers)>1): print('Need more data')
else: print('Incorrect data')

#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

numbers=set()
for i in range(10):
    for j in range(10):
        for k in range(10):
            for l in range(10):
                if(i!=j and i!=k and i!=l):
                    numbers.add(str(i)+str(j)+str(k)+str(l))

def count():
    possible=set()

    for num in numbers:
        cow=0
        bulls=0
        for i in range(4):
            for j in range(4):
                if(num[i]==n[j]):
                    if(i!=j): bulls+=1
                    else: cow+=1
        if(cow==x and bulls==y):
            possible.add(num)

    return possible

for _ in range(Int()):
    n,x,y=input().split()
    x=int(x)
    y=int(y)

    numbers=count()

if(len(numbers)==1): print(list(numbers)[0])
elif(len(numbers)>1): print('Need more data')
else: print('Incorrect data')

#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

numbers=set()
for i in range(10):
    for j in range(10):
        for k in range(10):
            for l in range(10):
                if(i!=j and j!=k and k!=l):
                    numbers.add(str(i)+str(j)+str(k)+str(l))

def count():
    possible=set()

    for num in numbers:
        cow=0
        bulls=0

        for i in range(4):
            for j in range(4):
                if(num[j]==n[i]):
                        bulls+=1
                        break
            if(num[i]==n[i]): cow+=1

        if(cow==x and bulls-cow==y):
            possible.add(num)

    return possible

for _ in range(Int()):
    n,x,y=input().split()
    x=int(x)
    y=int(y)

    numbers=count()

if(len(numbers)==1): print(list(numbers)[0])
elif(len(numbers)>1): print('Need more data')
else: print('Incorrect data')

'''input
2
0123 1 1
4567 1 2
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy

setrecursionlimit(15000)

def take_intersection():
	pass

def discover_digits(guess, index, final, base):
	if index == len(guess):
		final.append(list(base))
		return

	else:
		num, first, second = guess[index]
		first = int(first)
		second = int(second)
		num = list(map(int, list(num)))

		comb = combinations(num, first + second)
		for i in comb:
			i = list(i)
			cbase = deepcopy(base)
			for j in i:
				cbase.add(j)
			discover_digits(guess, index + 1, final, cbase)

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, answer):
	perm = permutations(answer)
	flag = 0
	ans = []
	for i in perm:
		if flag == 1:
			return ans
		i = list(i)
		for j in range(len(guess)):
			num = guess[j][0]
			if check(i, guess, j):
				pass
			else:
				flag = 0
				break
		else:
			flag = 1
			ans = i
	return ans

def check_invalid(final):
	for element in final:
		if len(element) > 4:
			pass
		else:
			return False
	return True

def check_unique(final):
	count = 0
	for element in final:
		if len(element) == 4:
			count += 1
	if count == 1:
		return True
	else:
		return False

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# getting ready final list
final = []
base = set()
discover_digits(guess, 0, final, base)

#print(final)
# checking for right answer

if check_unique(final):
	for element in final:
		if len(element) == 4:
			ans = get_answer(guess, element)
			if len(ans) == 4:
				for i in ans:
					print(i, end = '')
				exit()

if check_invalid(final):
	print("Incorrect data")
	exit()
else:
	print("Need more data")
	exit()

'''input
2
1263 1 2
8103 2 1
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy

setrecursionlimit(15000)

def take_intersection():
	pass

def discover_digits(guess, index, final, base):
	if index == len(guess):
		final.append(list(base))
		return

	else:
		num, first, second = guess[index]
		first = int(first)
		second = int(second)
		num = list(map(int, list(num)))

		comb = combinations(num, first + second)
		for i in comb:
			i = list(i)
			cbase = deepcopy(base)
			for j in i:
				cbase.add(j)
			discover_digits(guess, index + 1, final, cbase)

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, answer):
	while len(answer) < 4:
		answer.append(-1)
	perm = permutations(answer)
	flag = 0
	ans = []
	for i in perm:
		if flag == 1:
			return ans
		i = list(i)
		for j in range(len(guess)):
			num = guess[j][0]
			if check(i, guess, j):
				pass
			else:
				flag = 0
				break
		else:
			flag = 1
			ans = i
	return ans

def check_invalid(final):
	count = 0
	tans = []
	for element in final:
		if len(element) != 4:
			ans = get_answer(guess, element)
			if len(ans) > 0:
				return False
	return True

	if count == 1:
		for i in tans:
			print(i, end = '')
		return True
	else:
		return False

def check_unique(final):
	count = 0
	tans = []
	for element in final:
		if len(element) == 4:
			ans = get_answer(guess, element)
			if len(ans) == 4:
				tans = ans
				count += 1

	if count == 1:
		for i in tans:
			print(i, end = '')
		return True
	else:
		return False

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# getting ready final list
final = []
base = set()
discover_digits(guess, 0, final, base)

# print(final)
# checking for right answer

if check_unique(final):
	exit()
if check_invalid(final):
	print("Incorrect data")
	exit()
else:
	print("Need more data")
	exit()

'''input
2
1263 1 2
8103 2 1
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations

setrecursionlimit(15000)

def take_intersection(num, base, total, final, invalid, index):
	num = set(list(map(int, list((str(num))))))
	aux = []
	common = set(base).intersection(num)
	if 4 - len(base) >= total - len(common) and invalid[0] == True and index != 0:
		invalid[0] = False
	for i in common:
		final.add(i)
	if total == 4:
		invalid[0] = False
		for i in num:
			final.add(i)

		return aux
	else:
		com = combinations(num, total)
		for i in com:
			aux.append(list(i))
		return aux

def discover_digits(guess, final, index, digit, invalid):
	if index == len(guess):
		return

	else:
		if len(final) == 4:
			invalid[0] = False
			return

		num, first, second = guess[index]
		first = int(first); second = int(second)
		total = first + second

		digit_arr = take_intersection(num, digit, total, final, invalid, index)
		for i in digit_arr:
			discover_digits(guess, final, index + 1, i, invalid)

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, final, index, answer):
	perm = permutations(answer)
	flag = 0
	ans = []
	for i in perm:
		if flag == 1:
			return ans
		i = list(i)
		for j in range(len(guess)):
			num = guess[j][0]
			if check(i, guess, j):
				pass
			else:
				flag = 0
				break
		else:
			flag = 1
			ans = i

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# stage 1: Guess the digit
digit = []
final = set()
invalid = [True]
discover_digits(guess, final, 0, digit, invalid)
if invalid[0] == True:
	print("Incorrect data")
elif len(final) < 4:
	print("Need more data")
else:
# stage 2: towards the number
	answer = []
	for i in final:
		answer.append(i)
	ans = get_answer(guess, final, 0, answer)
	for i in ans:
		print(i, end= '')

'''input
6
1234 3 0
1235 3 0
1236 3 0
1237 3 0
1238 3 0
1239 3 0
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy

setrecursionlimit(15000)

def take_intersection():
	pass

def discover_digits(guess, index, final, base):
	if index == len(guess):
		if len(base) == 3:
			myset = {1, 2,3, 4, 5,6,7,8,9, 0}
			comb = combinations(myset, 4 - len(base))
			for i in comb:
				cbase = deepcopy(base)
				for j in i:
					cbase.add(j)
				final.append(cbase)

		else:
			final.append(list(base))
		return

	else:
		num, first, second = guess[index]
		first = int(first)
		second = int(second)
		num = list(map(int, list(num)))

		comb = combinations(num, first + second)
		for i in comb:
			i = list(i)
			cbase = deepcopy(base)
			for j in i:
				cbase.add(j)
			discover_digits(guess, index + 1, final, cbase)

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, answer):
	while len(answer) < 4:
		answer.append(-1)
	perm = permutations(answer)
	flag = 0
	ans = []
	for i in perm:
		if flag == 1:
			return ans
		i = list(i)
		for j in range(len(guess)):
			num = guess[j][0]
			if check(i, guess, j):
				pass
			else:
				flag = 0
				break
		else:
			flag = 1
			ans = i
	return ans

def check_invalid(final):
	count = 0
	tans = []
	for element in final:
		if len(element) != 4:
			ans = get_answer(guess, element)
			if len(ans) > 0:
				return False
	return True

	if count == 1:
		for i in tans:
			print(i, end = '')
		return True
	else:
		return False

def check_unique(final):
	count = 0
	tans = []
	for element in final:
		if len(element) == 4:
			ans = get_answer(guess, element)
			if len(ans) == 4:
				tans = ans
				count += 1

	if count >= 1:
		for i in tans:
			print(i, end = '')
		return True
	else:
		return False

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# getting ready final list
final = []
base = set()
discover_digits(guess, 0, final, base)

# print(final)
# checking for right answer
if check_unique(final):
	exit()
if check_invalid(final):
	print("Incorrect data")
	exit()
else:
	print("Need more data")
	exit()

'''input
2
0123 1 1
4567 1 2
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy

setrecursionlimit(15000)

def take_intersection():
	pass

def discover_digits(guess):
	myset = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
	flag = 0
	count = 0
	final = []
	comb = combinations(myset, 4)
	for i in comb:
		ans = get_answer(guess, list(i))
		if len(ans) == 4:
			count += 1
			final = ans
			flag = 1
	if count == 1:
		for i in final:
			print(i, end = '')
	elif count > 1:
		print("Need more data")
	if flag == 0:
		print("Incorrect data")

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, answer):
	while len(answer) < 4:
		answer.append(-1)
	perm = permutations(answer)
	flag = 0
	ans = []
	for i in perm:
		if flag == 1:
			return ans
		i = list(i)
		for j in range(len(guess)):
			num = guess[j][0]
			if check(i, guess, j):
				pass
			else:
				flag = 0
				break
		else:
			flag = 1
			ans = i
	return ans

def check_invalid(final):
	count = 0
	tans = []
	for element in final:
		if len(element) != 4:
			ans = get_answer(guess, element)
			if len(ans) > 0:
				return False
	return True

	if count == 1:
		for i in tans:
			print(i, end = '')
		return True
	else:
		return False

def check_unique(final):
	count = 0
	tans = []
	for element in final:
		if len(element) == 4:
			ans = get_answer(guess, element)
			if len(ans) == 4:
				tans = ans
				count += 1

	if count >= 1:
		for i in tans:
			print(i, end = '')
		return True
	else:
		return False

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# getting ready final list
final = []
base = set()
discover_digits(guess)

'''input
1
1234 0 0
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations

setrecursionlimit(15000)

def take_intersection(num, base, total, final, invalid, index):
	# print(base, total)
	num = set(list(map(int, list((str(num))))))
	aux = []
	common = set(base).intersection(num)
	if 4 - len(base) >= total - len(common) and invalid[0] == True:
		if index != 0 and len(guess) > 1:
			invalid[0] = False
		elif index == 0 and len(guess) == 1:
			invalid[0] = False
	for i in common:
		final.add(i)
	if total == 4:
		invalid[0] = False
		for i in num:
			final.add(i)

		return aux
	else:
		com = combinations(num, total)
		for i in com:
			aux.append(list(i))
		return aux

def discover_digits(guess, final, index, digit, invalid):
	if index == len(guess):
		return

	else:
		if len(final) == 4:
			invalid[0] = False
			return

		num, first, second = guess[index]
		first = int(first); second = int(second)
		total = first + second

		digit_arr = take_intersection(num, digit, total, final, invalid, index)
		for i in digit_arr:
			discover_digits(guess, final, index + 1, i, invalid)

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, final, index, answer):
	perm = permutations(answer)
	flag = 0
	ans = []
	for i in perm:
		if flag == 1:
			return ans
		i = list(i)
		for j in range(len(guess)):
			num = guess[j][0]
			if check(i, guess, j):
				pass
			else:
				flag = 0
				break
		else:
			flag = 1
			ans = i

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# stage 1: Guess the digit
digit = []
final = set()
invalid = [True]
discover_digits(guess, final, 0, digit, invalid)
if invalid[0] == True:
	print("Incorrect data")
elif len(final) < 4:
	print("Need more data")
else:
# stage 2: towards the number
	answer = []
	for i in final:
		answer.append(i)
	ans = get_answer(guess, final, 0, answer)
	for i in ans:
		print(i, end= '')

'''input
2
0123 1 1
4567 1 2
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy

setrecursionlimit(15000)

def take_intersection():
	pass

def discover_digits(guess, index, final, base):
	if index == len(guess):
		final.append(list(base))
		return

	else:
		num, first, second = guess[index]
		first = int(first)
		second = int(second)
		num = list(map(int, list(num)))

		comb = combinations(num, first + second)
		for i in comb:
			i = list(i)
			cbase = deepcopy(base)
			for j in i:
				cbase.add(j)
			discover_digits(guess, index + 1, final, cbase)

def check(arr, guess, index):
	first = 0
	total = 0
	second = 0
	for i in range(4):
		if arr[i] == int(guess[index][0][i]):
			first += 1
		if str(arr[i]) in guess[index][0]:
			total += 1
	second = total - first
	if first == int(guess[index][1]) and second == int(guess[index][2]):
		return True
	else:
		return False

def get_answer(guess, answer):
	perm = permutations(answer)
	flag = 0
	ans = []
	for i in perm:
		if flag == 1:
			return ans
		i = list(i)
		for j in range(len(guess)):
			num = guess[j][0]
			if check(i, guess, j):
				pass
			else:
				flag = 0
				break
		else:
			flag = 1
			ans = i
	return ans

def check_invalid(final):
	for element in final:
		if len(element) > 4:
			pass
		else:
			return False
	return True

def check_unique(final):
	count = 0
	tans = []
	for element in final:
		if len(element) == 4:
			ans = get_answer(guess, element)
			if len(ans) == 4:
				tans = ans
				count += 1

	if count == 1:
		for i in tans:
			print(i, end = '')
		return True
	else:
		return False

# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
	guess.append(list(map(str, stdin.readline().split())))

# getting ready final list
final = []
base = set()
discover_digits(guess, 0, final, base)

#print(final)
# checking for right answer

if check_unique(final):
	exit()
if check_invalid(final):
	print("Incorrect data")
	exit()
else:
	print("Need more data")
	exit()


In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.

The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths. The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW". The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.

Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.

NoteIn the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.In the second sample, no sequence of moves can get both marbles to the end.

def prefix(s):
    v = [0]*len(s)
    for i in range(1,len(s)):
        k = v[i-1]
        while k > 0 and s[k] != s[i]:
            k = v[k-1]
        if s[k] == s[i]:
            k = k + 1
        v[i] = k
    return v

n = int(input())
n-=1
s1 = input()
s2 = input()
opos = {'W':'E', 'E':'W', 'N':'S', 'S':'N'}
s3 = ''
for elem in s2:
    s3 += opos[elem]

s3  = s3[::-1]
s = s3 + '$' + s1

a = prefix(s)[2 * n]
if a == 0: print('YES')
else: print('NO')

from time import time

opposite = {
    'N': 'S',
    'S': 'N',
    'E': 'W',
    'W': 'E'
}
otr = str.maketrans(opposite)

bits = {
    'N': 0,
    'S': 1,
    'E': 2,
    'W': 3,
}

Q = 4294967291

def combine(h, v, q):
    return (h<<2 | v) % q

def combinel(h, v, q, s):
    return (v*s + h) % q

def flip(s):
    return ''.join(reversed(s.translate(otr)))

def solvable(p1, p2):
    h1 = 0
    h2 = 0
    s = 1
    for i in reversed(range(len(p1))):
        n1 = bits[p1[i]]
        n2 = bits[opposite[p2[i]]]
        h1 = combine(h1, n1, Q)
        h2 = combinel(h2, n2, Q, s)
        if h1 == h2 and p1[i:] == flip(p2[i:]):
            return False
        s = (s<<2) % Q
    return True

if __name__ == '__main__':
    n = int(input())
    p1 = input()
    p2 = input()
    print('YES' if solvable(p1, p2) else 'NO')

# Made By Mostafa_Khaled

import os

def main_entry():
    c2i = {'N':0, 'S':1, 'W':2, 'E':3}
    while True:
        try:
            n = int(raw_input())
        except ValueError:
            continue
        except EOFError:
            break
        a = str(raw_input())[::-1]
        b = str(raw_input())
        c = ''
        for k in a:
            c += str(c2i[k]^1)
        c += '#'
        for k in b:
            c += str(c2i[k])
        n = len(c)
        f = [-1 for i in xrange(n)]
        for i in range(1, n):
            k = f[i-1]
            while k>=0 and c[i]!=c[k+1]:
                k = f[k]
            if c[i]==c[k+1]:
                f[i] = k+1
        if f[n-1]==-1:
            print 'YES'
        else:
            print 'NO'

if __name__ == '__main__':
    main_entry()

def prefix(s):
    v = [0]*len(s)
    for i in range(1,len(s)):
        k = v[i-1]
        while k > 0 and s[k] != s[i]:
            k = v[k-1]
        if s[k] == s[i]:
            k = k + 1
        v[i] = k
    return v

n = int(input())
n-=1
s1 = input()
s2 = input()
opos = {'W':'E', 'E':'W', 'N':'S', 'S':'N'}
s3 = ''
for elem in s2:
    s3 += opos[elem]

s3[::-1]
s = s3 + '$' + s1

a = prefix(s)[2 * n]
if a == 0: print('YES')
else: print('NO')

import heapq

opposite = {
    'N': 'S',
    'S': 'N',
    'E': 'W',
    'W': 'E'
}

def move(m, i, p):
    if i < len(p) and m == p[i]:
        return i+1
    elif i > 0 and opposite[m] == p[i-1]:
        return i-1
    else:
        return i

def solvable(p1, p2):
    n = len(p1)
    pq = [(n, (0, 0))]
    seen = {(0, 0)}
    while pq:
        _, (i, j) = heapq.heappop(pq)
        print(p1[:i]+"|"+p1[i:])
        print(p2[:j]+"|"+p2[j:])
        print()
        if i == j == n:
            return True
        for m in 'NEWS':
            i_ = move(m, i, p1)
            j_ = move(m, j, p2)
            ij_ = i_, j_
            if ij_ not in seen:
                seen.add(ij_)
                heapq.heappush(pq, (n-min(i_, j_), ij_))
    return False

if __name__ == '__main__':
    n = int(input())
    p1 = input()
    p2 = input()
    print('YES' if solvable(p1, p2) else 'NO')

from time import time

opposite = {
    'N': 'S',
    'S': 'N',
    'E': 'W',
    'W': 'E'
}
otr = str.maketrans(opposite)

bits = {
    'N': 0,
    'S': 1,
    'E': 2,
    'W': 3,
}

Q = 4294967291

def combine(h, v, q):
    return (h<<2 | v) % q

def combinel(h, v, q, s):
    return (v*s + h) % q

def flip(s):
    return ''.join(reversed(s.translate(otr)))

def solvable(p1, p2):
    h1 = 0
    h2 = 0
    s = 0
    for i in reversed(range(len(p1))):
        n1 = bits[p1[i]]
        n2 = bits[opposite[p2[i]]]
        h1 = combine(h1, n1, Q)
        h2 = combinel(h2, n2, Q, s)
        if h1 == h2 and  p1[i:] == flip(p2[i:]):
            return False
        s = (s<<2) % Q
    return True

if __name__ == '__main__':
    n = int(input())
    p1 = input()
    p2 = input()
    print('YES' if solvable(p1, p2) else 'NO')

import os

def main_entry():
    c2i = {'N':0, 'S':1, 'W':2, 'E':3}
    while True:
        try:
            n = int(raw_input())
        except ValueError:
            continue
        except EOFError:
            break
        a = str(raw_input())
        b = str(raw_input())
        c = ''
        for k in a:
            c += str(c2i[k]^1)
        c += '#'
        for k in b:
            c += str(c2i[k])
        n = len(c)
        f = [-1 for i in xrange(n)]
        for i in range(1, n):
            k = f[i-1]
            while k>=0 and c[i]!=c[k+1]:
                k = f[k]
            if c[i]==c[k+1]:
                f[i] = k+1
        if f[n-1]==-1:
            print 'YES'
        else:
            print 'NO'

if __name__ == '__main__':
    main_entry()