import sys input = sys.stdin.readline from collections import Counter n=int(input()) DP=Counter() DP[-1]=0 for i in range(n): x,y=map(int,input().split()) NDP=Counter() if x==y: for dp in DP: score=DP[dp] if dp==x: score+=x score+=x NDP[x]=score else: for dp in DP: score=DP[dp] if x==dp: score+=x NDP[y]=max(NDP[y],score) score=DP[dp] if y==dp: score+=y NDP[x]=max(NDP[x],score) DP=NDP ANS=max(DP.values()) print(ANS)