n=int(input()) p1,p2=map(int,input().split()) q=[(p2==p1)*p2,(p1==p2)*p1] for _ in range(1,n): nq=[0,0] p3,p4=map(int,input().split()) nq[0]=max(q[0]+(p1==p4)*p1+(p3==p4)*p3,q[1]+(p2==p4)*p2+(p3==p4)*p3) nq[1]=max(q[0]+(p1==p3)*p1+(p3==p4)*p3,q[1]+(p2==p3)*p2+(p3==p4)*p3) q=nq p1,p2=p3,p4 print(max(q))