Problem:


Amida, the City of Miracle

奇跡の都市アミダ（Amida, the City of Miracle）の市長は他の市のように選挙で選ぶのではない．かつて長い政権闘争と天変地異により疲弊したこの都市は，候補者全員を公平に選び，かつ幸運の星の下に生まれた者を市長にするために，候補者全員の運命をくじにゆだねることにしたのである．後にあみだくじと呼ばれるくじである．

選挙は以下のように行われる．候補者数と同数の長い縦線が引かれ，さらにいくつかの横線がそこに引かれる．横線は隣接した縦線の途中同士を結ぶように引かれる．いずれかの縦線の下には「当選」と書かれている．どの縦線が当選であるかは候補者からわからないように隠される．それぞれの候補者は縦線を 1 つ選択する．全ての候補者の選択が終わると，各候補者は線を上から下に向かってたどる．ただし，移動途中に横線が見つかったときは，横線の接続された反対側の縦線に移り，また下に向かってたどる．縦線の一番下までたどり着いたときに，そこに「当選」と書かれていた者が当選して，次期市長となる．

この方法はうまくいった．幸運な市長の下に，争いも災害も少ない平和な時代が続いた．しかし近年，人口増加のためにこの手法に限界が見えてきた．候補者が増えたため，あみだくじが大規模になり，手作業による集計では非常に時間がかかるようになったのである．そこで市では，市役所のプログラマーであるあなたにあみだくじの電算化を依頼した．

あなたの仕事は，あみだくじの構造と，選択された縦線の位置が与えられたときに，最終的にどの縦線にたどり着くかを求めるプログラムを書くことである．

以下の図は，サンプルとして与えた入力および出力の内容を示したものである．

Input

入力は複数のデータセットからなる．1 つのデータセットは以下のように与えられる．

n m a

横線1

横線2

横線3

...

横線m

n ，m ，a はそれぞれ 2 <= n <= 100, 0 <= m <= 1000, 1 <= a <= n をみたす整数であり，それぞれ縦線の本数，横線の本数，調べる縦線の番号を表す．

横線のデータは以下のように与えられる．

h p q

h ，p ，q はそれぞれ 1 <= h <= 1000, 1 <= p < q <= n, を満たす整数であり，h はその横線の高さ，p ，q はその横線につながっている 2 本の縦線の番号を表す．

1 つの縦線の同じ高さに，異なる横線が 2 つ以上つくことはない．

入力の終わりには，空白で区切られた 3 つのゼロのみからなる行がある。

Output

それぞれのデータセットに対して 1 行ずつ，縦線 a の上端からたどったときの下端における縦線の番号を出力しなさい．

Sample Input

4 4 1
3 1 2
2 2 3
3 3 4
1 3 4
0 0 0

Output for the Sample Input

4



Sample input:
4 4 1
3 1 2
2 2 3
3 3 4
1 3 4
0 0 0


Sample output:
4

Submission status: Wrong Answer

Solution code:
n,m,a = list(map(int,input().split(' ')))
td ={}
high =0
for i in range(n):
    td[i] =[]
for _ in range(m):
    h,p,q = list(map(int,input().split(' ')))
    td[p-1].append((h,q))
    if h > high:high =h 
for i in range(n):
    sorted(td[i])

current = a-1
while 0!=len(td[current]):

    edge = td[current].pop()
    if high == edge[0]:
        current = edge[1] -1
        high -=1
    elif high > edge[0]:
        high = edge[0]
        current = edge[1]-1
    
print(current+1)

Submission status: Wrong Answer

Solution code:
while 1:
    n,m,a = list(map(int,input().split(' ')))
    if n==0:break
    td ={}
    high =0
    for i in range(n):
        td[i] =[]
    for _ in range(m):
        h,p,q = list(map(int,input().split(' ')))
        td[p-1].append((h,q))
        if h > high:high =h 
    for i in range(n):
        sorted(td[i])

    current = a-1
    while 0!=len(td[current]):

        edge = td[current].pop()
        if high == edge[0]:
            current = edge[1] -1
            high -=1
        elif high > edge[0]:
            high = edge[0]
            current = edge[1]-1
        
    print(current+1)

Submission status: Wrong Answer

Solution code:
while 1:
    n,m,a = list(map(int,input().split(' ')))
    if n ==0:break
    td ={}
    high =0
    for i in range(n):
        td[i] =[]
    for _ in range(m):
        h,p,q = list(map(int,input().split(' ')))
        td[p-1].append((h,q))
        td[q-1].append((h,p))
        if h > high:high =h 
    for i in range(n):
        sorted(td[i])
    current = a-1
    while 0!=len(td[current]):
        edge = td[current].pop()
        if high == edge[0]:
            current = edge[1] -1
            high -=1
        elif high > edge[0]:
            high = edge[0]
            current = edge[1]-1
        
    print(current+1)

Submission status: Wrong Answer

Solution code:
import sys
def search(x,y,lb,ub,field):
	if y == ub[1] :
		number = x
	elif lb[0] < x - 1 and field[y][x-1] == 1:
		number = search(x-2, y+1, lb, ub, field)
	elif ub[0] > x + 1 and field[y][x+1] == 1:
		number = search(x+2, y+1, lb, ub, field)
	else :
		number = search(x, y+1, lb, ub, field)
	return number

sys.setrecursionlimit(10000)
while 1:
	n, m, a = map(int, raw_input().split(" "))
	if (n,m,a) == (0,0,0):
		break
	amida = [[0 if i % 2 == 0 else 1 for i in range(n*2)] for j in range(1001)]
	for j in range(m):
		h,p,q = map(int, raw_input().split(" "))
		amida[10-h][p * 2] = 1
	print (search(2*a-1, 0, (1, 0), (2*n-1, 1000), amida) + 1) / 2

Submission status: Wrong Answer

Solution code:
import itertools

while True:
	n, m, a = map(int, input().split())
	if (n,m,a) == (0,0,0):
		break
	hpq = [list(map(int, input().split())) for i in range(m)]
	hpq = sorted(hpq, reverse=True)
	for k, g in itertools.groupby(hpq, key=lambda x:x[0]):
		for gg in g:
			if a == gg[1]:
				a = gg[2]
				break
			elif a == gg[2]:
				a == gg[1]
				break
	print(a)

Submission status: Wrong Answer

Solution code:
currentPlace = []
height = 0

def get_input():
    while True:
        try:
            a = input()
            if a == "0 0 0":
                break
            yield ''.join(a.split())

        except EOFError:
            break
if __name__ == '__main__':
    array = list(get_input())
    who = array[0][2]
    del array[0]
    array = sorted(array,key = lambda x:x[0],reverse = True)
    height = array[0][0]
    currentPlace = [int(height),int(who)]
    #print("??±???array???{0}".format(array))

    #??¢????????????????????????????????????
    for i in range(len(array)):
        currentPlace[0] = int(array[i][0])
        #print("?????¨?????????{0}".format(currentPlace))
        #print(currentPlace)
        if (int(array[i][0]) == currentPlace[0]
        and (int(array[i][1]) == currentPlace[1]
        or int(array[i][2]) == currentPlace[1])):
            print("array[{0}]???{1}".format(i,array[i]))
            if int(array[i][1]) == currentPlace[1]:
                currentPlace[1] = int(array[i][2])
            else:
                currentPlace[1] = int(array[i][1])
            #print("?????¨?????????{0}????§????".format(currentPlace))

    print(currentPlace[1])

Submission status: Wrong Answer

Solution code:
currentPlace = []
height = 0

def get_input():
    while True:
        try:
            a = input()
            if a == "0 0 0":
                break
            yield ''.join(a.split())

        except EOFError:
            break
if __name__ == '__main__':
    array = list(get_input())
    who = array[0][2]
    del array[0]
    array = sorted(array,key = lambda x:x[0],reverse = True)
    height = array[0][0]
    currentPlace = [int(height),int(who)]
    #print("??±???array???{0}".format(array))

    #??¢????????????????????????????????????
    for i in range(len(array)):
        currentPlace[0] = int(array[i][0])
        #print("?????¨?????????{0}".format(currentPlace))
        #print(currentPlace)
        if (int(array[i][0]) == currentPlace[0]
        and (int(array[i][1]) == currentPlace[1]
        or int(array[i][2]) == currentPlace[1])):
            #print("array[{0}]???{1}".format(i,array[i]))
            if int(array[i][1]) == currentPlace[1]:
                currentPlace[1] = int(array[i][2])
            else:
                currentPlace[1] = int(array[i][1])
            #print("?????¨?????????{0}????§????".format(currentPlace))

    print(currentPlace[1])

Submission status: Wrong Answer

Solution code:
n,m,a = map(int,input().split())
f = [[0]*m for _ in range(n)]
for _ in range(m):
    h,p,q = map(int,input().split())
    f[p-1][m-h-1] = 1
    f[q-1][m-h-1] = -1
a = 0
for i in range(len(f[0])): a = f[a][i]+a
print(a+1)

Submission status: Wrong Answer

Solution code:
n,m,a = map(int,input().split())
A = [[0]*1001 for i in range(n + 1)]


for i in range(m):
	h,p,q = map(int,input().split())
	A[p][1000 - h] = q
	A[q][1000 - h] = p
	
for i in range(1000):
	if A[a][i] == 0:
		pass
	else:
		a = A[a][i]
print(a)

Submission status: Wrong Answer

Solution code:
N,M,A = map(int,input().split())
amida = [[] for i in range(1000)]
for i in range(M):
    h,p,q = map(lambda s:int(s)-1,input().split())
    amida[h].append((p,q))
    amida[h].append((q,p))
input() #ignore

now = A-1
for es in reversed(amida):
    for a,b in es:
        if a == now:
            now = b
            break
print(now + 1)

Submission status: Wrong Answer

Solution code:
N,M,A = map(int,input().split())
amida = [[] for i in range(1001)]
for i in range(M):
    h,p,q = map(int,input().split())
    amida[h].append((p,q))
input() #ignore

now = A
for es in reversed(amida):
    for a,b in es:
        if a == now:
            now = b
            break
        elif b == now:
            now = a
            break
print(now)

Submission status: Wrong Answer

Solution code:
n, m, a = map(int, input().split(' '))
hl = []
while True:
    h, p, q = map(int, input().split(' '))
    if h == 0 and p == 0 and q == 0:
        break
    hl.append([h, p, q])
hl.sort(key=lambda x:x[0], reverse=True)
vl = a
for l in hl:
    if l[1] == vl:
        vl = l[2]
    elif l[2] == vl:
        vl = l[1]
print(vl)

Submission status: Wrong Answer

Solution code:
while True:
    n, m, a = [int(x) for x in raw_input().strip().split()]
    if n < 2 or a < 1:
        break
    lines = []
    for i in xrange(m):
        h, p, q = [int(x) for x in raw_input().strip().split()]
        lines.append([h, p, q])

    verticals = [[] for i in xrange(n)]
    for i in xrange(n):
        for l in lines:
            if l[1] == i + 1 or l[2] == i + 1:
                verticals[i].append(l)
                t = sorted(verticals[i], reverse = True)
                verticals[i] = t

height = 10000
pos = a
while True:
    for line in verticals[pos - 1]:
        if line[0] < height:
            height = line[0]
            if line[1] == pos:
                pos = line[2]
            else:
                pos = line[1]
            break
    print pos + 1
    break

Submission status: Wrong Answer

Solution code:
while True:
    n, m, a = [int(x) for x in raw_input().strip().split()]
    if n < 2 or a < 1:
        break
    lines = []
    for i in xrange(m):
        h, p, q = [int(x) for x in raw_input().strip().split()]
        lines.append([h, p, q])

    verticals = [[] for i in xrange(n)]
    for i in xrange(n):
        for l in lines:
            if l[1] == i + 1 or l[2] == i + 1:
                verticals[i].append(l)
                t = sorted(verticals[i], reverse = True)
                verticals[i] = t

    height = 10000
    pos = a
    while True:
        for line in verticals[pos - 1]:
            if line[0] < height:
                height = line[0]
                if line[1] == pos:
                    pos = line[2]
                else:
                    pos = line[1]
                break
        print pos + 1
        break

Submission status: Wrong Answer

Solution code:
while True:
    n, m, a = map(int, raw_input().split())
    if n == 0:
        break
    bar = []
    for i in xrange(m):
        h, p, q = map(int, raw_input().split())
        bar.append((h, p, q))
    bar.sort(reverse=True)
    last = 200
    cur = a
    for b in bar:
        if b[0] < last:
            if b[1] == cur:
                cur = b[2]
                last = b[0]
            elif b[2] == cur:
                cur = b[1]
                last = b[0]
    print cur

Submission status: Wrong Answer

Solution code:
while True:
    n, m, a = map(int, raw_input().split())
    if n == 0:
        break
    bar = []
    for i in xrange(m):
        h, p, q = map(int, raw_input().split())
        bar.append((h, p, q))
    bar.sort(key = lambda x: -x[0])
    last = 200
    cur = a
    for b in bar:
        if b[0] < last:
            if b[1] == cur:
                cur = b[2]
                last = b[0]
            elif b[2] == cur:
                cur = b[1]
                last = b[0]
    print cur

Submission status: Accepted

Solution code:
while 1:
    n,m,a = list(map(int,input().split(' ')))
    if n ==0:break
    td ={}
    high =0
    for i in range(n):
        td[i] =[]
    for _ in range(m):
        h,p,q = list(map(int,input().split(' ')))
        td[p-1].append((h,q))
        td[q-1].append((h,p))
        if h > high:high =h 
    for i in range(n):
        td[i] = sorted(td[i],key = lambda edge:edge[0])
    current = a-1
    while 0!=len(td[current]):
        edge = td[current].pop()
        if high == edge[0]:
            current = edge[1] -1
            high -=1
        elif high > edge[0]:
            high = edge[0] -1
            current = edge[1]-1
        if high ==0:break
    print(current+1)

Submission status: Accepted

Solution code:
while True:
  n, m, a = map(int, input().split())
  if n == 0:
    break
  edges = [[] for _ in range(1001)]
  for _ in range(m):
    h, p, q = map(int, input().split())
    edges[h].append((p, q))
  
  for h in range(1000, -1, -1):
    if (a, a + 1) in edges[h]:
      a = a + 1
    elif (a - 1, a) in edges[h]:
      a = a - 1
  print(a)

Submission status: Accepted

Solution code:
# coding: utf-8

def main():
  while True:
    (n, m, a) = map(int, raw_input().split(' '))
    if (n, m, a) == (0, 0, 0): break

    bars = []
    for i in range(m):
      (h, p, q) = map(int, raw_input().split(' '))
      bars.append((h, p, q))

    x = a
    while True:
      # Down step by step, and above bars are removed in each step
      # To handle straight down case (no possible bars), next_bar can be (0,x,x)
      next_bar = max([b for b in bars if b[1] == x or b[2] == x] + [(0, x, x)])
      x = next_bar[2] if next_bar[1] == x else next_bar[1]
      y = next_bar[0]
      map(lambda b: bars.remove(b), [b for b in bars if b[0] >= y])
      if bars == []: break
    print x

if __name__ == '__main__':
  main()

Submission status: Accepted

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

import os
import sys
import itertools
import math
from collections import Counter, defaultdict

class Main(object):
    
    def __init__(self):
        pass

    def solve(self):
        '''
        insert your code
        '''
        while True:
            n, m, a = map(int, raw_input().split())
            if n == 0 and m == 0 and a == 0:
                break
            adj = []
            for i in range(m):
                h, p, q = map(int, raw_input().split())
                adj.append((h, p, q))
            adj.sort(reverse=True)
            # print adj
            for h, p, q in adj:
                if p == a:
                    a = q
                elif q == a:
                    a = p
            print a
        return None

if __name__ == '__main__':
    m = Main()
    m.solve()

Submission status: Accepted

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

while True:
    n,m,a = map(int,input().split(" "))
    if n==0 and m==0 and a==0:
        break
    lines = []
    for i in range(m):
        h,p,q = map(int,input().split(" "))
        lines.append((h,p,q))

    pos = a
    for h,q,p in list(reversed(sorted(lines))):
        if pos == p:
            pos = q
        elif pos == q:
            pos = p
    print(pos)

Submission status: Accepted

Solution code:
import sys
def search(x,y,lb,ub,field):
	if y == ub[1] :
		number = x
	elif lb[0] < x - 1 and field[y][x-1] == 1:
		number = search(x-2, y+1, lb, ub, field)
	elif ub[0] > x + 1 and field[y][x+1] == 1:
		number = search(x+2, y+1, lb, ub, field)
	else :
		number = search(x, y+1, lb, ub, field)
	return number

sys.setrecursionlimit(10000)
while 1:
	n, m, a = map(int, raw_input().split(" "))
	if (n,m,a) == (0,0,0):
		break
	amida = [[0 if i % 2 == 0 else 1 for i in range(n*2)] for j in range(1001)]
	for j in range(m):
		h,p,q = map(int, raw_input().split(" "))
		amida[1000-h+1][p * 2] = 1
	print (search(2*a-1, 0, (1, 0), (2*n-1, 1001), amida) + 1) / 2

Submission status: Accepted

Solution code:
while(1):
    [n,m,a]=[int(x) for x in raw_input().split()]
    if n==0:
        break
    else:
        currenth=9999999
        amidadict={}
        for i in range(n):
            amidadict[i+1]=[] #amidadict[i]=[(height,direction)]
        for i in range(m): 
            [h,p,q]=[int(x) for x in raw_input().split()]
            amidadict[p].append((h,q))
            amidadict[q].append((h,p))
        for i in range(n):
            amidadict[i+1].sort(key=lambda x:x[0])
        while(len(amidadict[a])>0):
            topamida=amidadict[a].pop()
            if topamida[0]<currenth:
                a=topamida[1]
                currenth=topamida[0]
        print a

Submission status: Accepted

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

(n, m, a) = map(int, raw_input().split())
while n!=0:
    ami = []
    for i in range(m):
        ami.append(map(int, raw_input().split()))
    ami.sort()
    ami.reverse()

    for i in range(m):
        if ami[i][1] == a:
            a = ami[i][2]
        elif ami[i][2] == a:
            a = ami[i][1]

    print a
    (n, m, a) = map(int, raw_input().split())

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, input().split())
    if n == 0: break
    ls = [[0 for i in range(n+1)] for i in range(1001)]
    for i in range(m):
        h, p, q = map(int, input().split())
        ls[h][p] = 1
    ls.reverse()
    for t in ls:
        if t[a] == 1:
            a += 1
        elif t[a-1] == 1:
            a -= 1
    print(a)

Submission status: Accepted

Solution code:
import operator
import sys
f = sys.stdin

while True:
    n, m, a = map(int, f.readline().split())
    if n == 0:
        break 
    amida = [i for i in range(n + 1)]
    lines = [list(map(int, f.readline().split())) for _ in range(m)]
    lines.sort(key=operator.itemgetter(0))
    for _, p, q in lines:
        amida[p], amida[q] = amida[q], amida[p]
    
    print(amida[a])

Submission status: Accepted

Solution code:
def main():
    while True:
        n,m,a = [int(x) for x in input().split()]
        if n==0 and m==0 and a==0:
            return
        L = []
        for i in range(m):
            h,p,q = [int(x) for x in input().split()]
            L.append((h,p-1,q-1))
        L.sort()
        res = [i+1 for i in range(n)]
        for l in L:
            res[l[1]], res[l[2]] = res[l[2]], res[l[1]]
        print(res[a-1])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

while True:
	n, m, a = map(int, input().split())
	if (n,m,a) == (0,0,0):
		break
	hpq = [list(map(int, input().split())) for i in range(m)]
	hpq = sorted(hpq, reverse=True)
	for k, g in itertools.groupby(hpq, key=lambda x:x[0]):
		for gg in g:
			if a == gg[1]:
				a = gg[2]
				break
			elif a == gg[2]:
				a = gg[1]
				break
	print(a)

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, input().split())
    if not n:
        break
    bars = [tuple(map(int, input().split())) for _ in range(m)]
    bars_h = [set() for _ in range(max(bars)[0])]
    for h, p, q in bars:
        bars_h[h - 1].add((p - 1, q - 1))

    amida = list(range(n))
    for bar_h in bars_h:
        for p, q in bar_h:
            amida[p], amida[q] = amida[q], amida[p]
    print(amida[a - 1] + 1)

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    while True:
        n, m, a = map(int, raw_input().split())
        if n == 0 and m == 0 and a == 0:
            break

        now = a
        amida = [[] for i in range(1001)]

        for i in range(m):
            h, p, q = map(int, raw_input().split())
            amida[h].append((p, q))
        
        for height in range(1000 - 1, 0, -1):
            lines = amida[height]
            for l in lines:
                if l[0] == now:
                    now = l[1]
                elif l[1] == now:
                    now = l[0]

        print now

Submission status: Accepted

Solution code:
while True:
  n,m,a = tuple(map(int,input().split()))
  if n==0 and m==0 and a == 0:
    break
  l = []
  max_h = 0

  for i in range(m):
    h,p,q = tuple(map(int,input().split()))
    if max_h < h:
      max_h = h
    l.append([h,p,q])
  pos = max_h
  while pos > 0:
    for i in l:
      if i[0]==pos:
        if a == i[2]:
          a = i[1]
        elif a == i[1]:
          a = i[2]
    pos -= 1
  print(a)

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, input().split())

    if n + m + a == 0:
        break

    lines = list(sorted([tuple(map(int, input().split())) for _ in range(m)]))

    replace = list(range(1, n+1))

    for l in lines:

        _, p, q = l

        p -= 1
        q -= 1

        replace[p], replace[q] = replace[q], replace[p]

    print(replace[a-1])

Submission status: Accepted

Solution code:
while True:
    [n,m,a]=input().split()
    if [n,m,a]==["0","0","0"]: break
    [n,m]=[int(n),int(m)]
    yokobo={}
    for k in range(m):
        [h,p,q]=input().split()
        yokobo[h,p]=q
        yokobo[h,q]=p
    high=1000
    while high>0:
        if (str(high),a) in yokobo:
            a=yokobo[str(high),a]
        high-=1
    print(a)

Submission status: Accepted

Solution code:


while True:
    # num_columns: ????£?????????°
    # num_lines: ?¨??£?????????°(???????????????2????´???????????????°)
    # entry: ????????????????????????????§?????????´????????????
    num_columns, num_lines, entry = map(int, input().split())

    if num_columns == 0 and num_lines == 0 and entry == 0:
        break

    lines = []
    for _ in range(num_lines):
        height, p, q = map(int, input().split())
        lines.append((height, p-1, q-1)) # ????????????0?????????????§????????????§???????????????

    # lines??????????????????????????§???????????????????????????????´?????¨??£???????????????\???????????§
    # ??????????????????????????°??????????????????????????????
    lines.sort()
    lines.reverse()
    # ??????2??????????????§???lines????????????????´??????§?????????????????¶

    result = list(range(1, num_columns+1)) # ??????????§????????????´????????¨????????????

    for line in lines:
        height, p, q = line
        
        # ?????????`replace`???p????????¨q?????????????????????
        result[p], result[q] = result[q], result[p]

    for index, element in enumerate(result):
        if element == entry:
            print(index + 1) # ????????????0?????????????§????????????§???????????????
            break
    # print(result.index(entry) + 1) ??§?????????

Submission status: Accepted

Solution code:
currentPlace = []
array = []
height = 0
start = 0
abs_len = 0

def get_input():
    array = []
    N = []
    while True:
        try:
            str1,str2,str3 = input().split()
            int1,int2,int3 = int(str1),int(str2),int(str3)
            if int1 == 0 and int2 == 0 and int3 == 0:
                break
            yield [int1,int2,int3]
        except EOFError:
            break

if __name__ == '__main__':
    array_total = list(get_input())
    #print(array)
    while True:
        #print("start???{0}".format(start))
        height = array_total[start][1]
        who = array_total[start][2]
        array = array_total[start:start+height+1]
        #print(array)
        #print("height???{0}".format(height))

        #print("?????????{0}".format(array[start]))
        #??¢????????????????????????????????????
        currentPlace = [height,who]
        #print("??±???array???{0}".format(array))
        del array[0]
        array.sort(key = lambda x:x[0],reverse = True)
        #print(array)

        for i in range(len(array)):
            currentPlace[0] = int(array[i][0])
            #print("?????¨?????????{0}".format(currentPlace))
            #print(currentPlace)
            if (int(array[i][0]) == currentPlace[0]
            and (int(array[i][1]) == currentPlace[1]
            or int(array[i][2]) == currentPlace[1])):
                if int(array[i][1]) == currentPlace[1]:
                    currentPlace[1] = int(array[i][2])
                else:
                    currentPlace[1] = int(array[i][1])
                #print("?????¨?????????{0}????§????".format(currentPlace))

        print(currentPlace[1])
        #?¬??????¢???????????????????????????start?????£??\

        start = start + height + 1
        abs_len = abs_len + height + 1
        #print(abs_len)
        del array[:]

        if abs_len + 1 > len(array_total):
            break

Submission status: Accepted

Solution code:
currentPlace = []
array = []
height = 0
start = 0
abs_len = 0

def get_input():
    array = []
    N = []
    while True:
        try:
            str1,str2,str3 = input().split()
            int1,int2,int3 = int(str1),int(str2),int(str3)
            if int1 == 0 and int2 == 0 and int3 == 0:
                break
            yield [int1,int2,int3]
        except EOFError:
            break

if __name__ == '__main__':
    array_total = list(get_input())
    while True:
        height = array_total[start][1]
        who = array_total[start][2]
        array = array_total[start:start+height+1]

        currentPlace = [height,who]
        del array[0]
        array.sort(key = lambda x:x[0],reverse = True)

        for i in range(len(array)):
            currentPlace[0] = int(array[i][0])
            if (int(array[i][0]) == currentPlace[0]
            and (int(array[i][1]) == currentPlace[1]
            or int(array[i][2]) == currentPlace[1])):
                if int(array[i][1]) == currentPlace[1]:
                    currentPlace[1] = int(array[i][2])
                else:
                    currentPlace[1] = int(array[i][1])

        print(currentPlace[1])

        start = start + height + 1
        abs_len = abs_len + height + 1
        del array[:]

        if abs_len + 1 > len(array_total):
            break

Submission status: Accepted

Solution code:
while 1:
    n, m, a = map(int, raw_input().split())
    if not n: break
    V = [map(int, raw_input().split()) for i in xrange(m)]
    V.sort()
    r = range(n+1)
    for h, p, q in V:
        r[p], r[q] = r[q], r[p]
    print r[a]

Submission status: Accepted

Solution code:
while True:
  n,m,a = map(int, raw_input().split())
  if n==m==a==0: break
  lst = [0] * n
  for i in xrange(n):
    lst[i] = i
  ms = {}
  for _ in xrange(m):
    h,p,q = map(int, raw_input().split())
    if h not in ms:
      ms[h] = {}
    ms[h][p] = q
  for i,v in sorted(ms.items()):
    for k,l in v.items():
      tmp = lst[k-1]
      lst[k-1] = lst[l-1]
      lst[l-1] = tmp
  print lst[a-1]+1

Submission status: Accepted

Solution code:
import sys

inf = 1<<30

def solve():
    while 1:
        n, m, a = map(int, sys.stdin.readline().split())

        if n == m == a == 0:
            return

        amida = [tuple(map(int, sys.stdin.readline().split())) for i in range(m)]
        amida.sort()

        while amida:
            h, p, q = amida.pop()

            if p == a:
                a = q
            elif q == a:
                a = p

        print(a)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
while True:
	n,m,a = map(int,input().split())
	if n == m == a == 0:
		break
	A = [[0]*1002 for i in range(n + 1)]
	for i in range(m):
		h,p,q = map(int,input().split())
		A[p][1001 - h] = q
		A[q][1001 - h] = p
		
	for i in range(1001):
		if A[a][i] == 0:
			pass
		else:
			a = A[a][i]
	print(a)

Submission status: Accepted

Solution code:
while (True):
    [n, m, a] = list(map(int, input().split()))
    '''
    n: num of vertical bars
    m: num of horizontal lines
    a: bar number to check
    '''
    if [n, m, a] == [0, 0, 0]:
        # terminate
        break

    hashDict = dict()
    maxHeight = -1
    for lineNumber in range(m):
        [h, p, q] = list(map(int, input().split()))
        maxHeight = max(maxHeight, h)
        hashDict[(h, p)] = q
        hashDict[(h, q)] = p

    # Start from the max height
    currentBar = a
    for height in range(maxHeight, 0, -1):
        if (height, currentBar) in hashDict.keys():
            currentBar = hashDict[(height, currentBar)]

    print(currentBar)

Submission status: Accepted

Solution code:
while True:
    N,M,A = map(int,input().split())
    if N == 0: break
    amd = [{} for i in range(1001)]
    for i in range(M):
        h,p,q = map(int,input().split())
        amd[h][p] = q
        amd[h][q] = p

    now = A
    for d in reversed(amd):
        if now in d:
            now = d[now]
    print(now)

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, input().split(' '))
    if n == 0 and m == 0 and a == 0:
        break
    hl = [list(map(int, input().split(' '))) for i in range(m)]
    hl.sort(key=lambda x: x[0], reverse=True)
    vl = a
    for l in hl:
        if l[1] == vl:
            vl = l[2]
        elif l[2] == vl:
            vl = l[1]
    print(vl)

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, raw_input().split())

    if n == 0 and m == 0 and a == 0:
        break

    hl = [map(int, raw_input().split()) for _ in range(m)]
    hl.sort(key=lambda x:x[0], reverse=True)

    ans = a

    for i in range(m):
        if ans == hl[i][1]:
            ans = hl[i][2]
        elif ans == hl[i][2]:
            ans = hl[i][1]

    print ans

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, raw_input().split())

    if n == 0 and m == 0 and a == 0:
        break

    hl = [map(int, raw_input().split()) for _ in range(m)]
    hl.sort(reverse=True)

    ans = a

    for i in range(m):
        if ans == hl[i][1]:
            ans = hl[i][2]
        elif ans == hl[i][2]:
            ans = hl[i][1]

    print ans

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, input().split())
    if n == m == a == 0:
        break

    lines = [list(map(int, input().split())) for i in range(m)]
    lines.sort()

    place = [i for i in range(n + 1)]
    for line in lines:
        h, p, q = line
        place[p], place[q] = place[q], place[p]

    print(place[a])

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    rr = []

    while True:
        n,m,a = LI()
        if n == 0:
            break
        t = sorted([LI_() for _ in range(m)], reverse=True)
        r = list(range(n))
        for h,p,q in t:
            r[p],r[q] = r[q],r[p]

        rr.append(r.index(a-1)+1)

    return '\n'.join(map(str, rr))


print(main())

Submission status: Accepted

Solution code:
while True:
	n, m, a = map(int, raw_input().split())
	if n == m == a == 0: break
	hl = [tuple(map(int, raw_input().split())) for i in xrange(m)]
	hl.sort(lambda x, y: cmp(y, x))
	for h, p, q in hl:
		if p == a: a = q
		elif q == a: a = p
	print a

Submission status: Accepted

Solution code:
import sys
while 1:
        n,m,a = map(int, raw_input().split())
        if not(n or m or a): break
        amida = [range(1,n+1) for i in xrange(1001)]
        l = []
        if m == 0: print a
        else:
                for i in xrange(m):
                        h,p,q = map(int, raw_input().split())
                        l.append((h,p,q))
                        
                l.sort(reverse=True)
                #print sys.stderr, l
                temp = a
                for i in xrange(len(l)):
                        if l[i][1] is temp:
                                temp = l[i][2]
                        elif l[i][2] is temp:
                                temp = l[i][1]

                print temp

Submission status: Accepted

Solution code:
while True:
    n, m, a = map(int, raw_input().split())
    if n == 0:
        break
    bar = [[-1 for i in xrange(n + 1)] for j in xrange(1001)]
    for i in xrange(m):
        h, p, q = map(int, raw_input().split())
        bar[h][p] = q
        bar[h][q] = p
    
    cur = a
    
    for i in xrange(1000, -1, -1):
        if bar[i][cur] != -1:
            cur = bar[i][cur]
    print cur