Problem:
Problem B
Leave No One Behind
A card game similar to Old Maid is played by
n
players
P
1
, ..., and
P
n
,
sitting clockwise in this order.
For this game,
n
pairs of cards numbered 1 through
n
are used.
    Each player has two cards at hand to start with.
First, any player who has a pair of cards with the same number discards them.
    If by chance all the players discard the cards in hand, the game ends.
    Otherwise, the following actions are repeated until the game ends.
    Note that, from now on, for a player
p,
the next player
means the player closest to
p
in the clockwise direction
    among those who still have one or more cards at that point in time.
Choose the player
p
as follows.
For the first turn, choose
P
1
.
          If, however,
P
1
has no cards, choose the next player of
P
1
.
For the second and subsequent turns, choose the next player of the one chosen for the previous turn.
The next player of
p
, say
p′,
looks at the card(s) in the hand of
p
and draws the one having the smallest number among them.
If that makes a pair of cards with the same number in the hand of
p′
, the pair is discarded.
      If no cards remain in any players' hands at this point, the game ends.
Figure B-1 shows the initial hands of the three players of the second dataset in Sample Input.
    Immediately after, the player
P
1
discards the two cards in the hand.
p
of the first turn is
P
2
because
P
1
has no cards.
Figure B-1: The initial hands of the second dataset in Sample Input
Figure B-2 shows the hands of the five players of the last dataset in Sample Input after the following actions:
P
1
is chosen first and the next player of
P
1
, that is,
P
2
, draws the card with the smallest number 1 from the
P
1
's hand.
P
2
has three cards with numbers 1, 3, and 5 in hand at the end of this turn;
P
3
,
P
4
, and
P
5
, in this order, draw the same card with the number 1 that was initially in the
P
1
's hand; and
P
5
discards the pair of cards with the number 1.
After this,
P
1
draws the only remaining card in
P
5
's hand and discards the drawn card and the card with the same number 2 in the hand.
    The player to be drawn from the hand next is the next player of
P
5
, which is
P
2
because
P
1
's hand is empty now.
Figure B-2: The hands of the last dataset in Sample Input after the fourth turn
Since at least one pair of cards is discarded between two drawings from the hand of the same player, the game will end sooner or later.
    Unlike Old Maid, no cards will be left in the hand of any player at the end.
Write a program that, for given initial hands of all the players,
    computes the number of times cards are drawn by the end of the game.
Input
The input consists of multiple datasets, each in the following format.
n
c
1,1
c
1,2
⋮
c
n
,1
c
n
,2
n
is the number of players.
n
is an integer no less than two and no more than 1000.
c
i
,1
and
c
i
,2
are the numbers on the two cards in the initial hand of
P
i
(1 ≤
i
≤
n
).
    Each integer between 1 and
n,
inclusive
...(truncated)

Submitted solutions:

code_snippet: #include <iostream>
#include <iomanip>
#include <vector>
#include <math.h>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
#include <cassert>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define all(a) a.begin(), a.end()
#define arr(a) a.rbegin(), a.rend()
template<typename T> bool chmin(T& a, T b){if(a > b){a = b; return true;} return false;}
template<typename T> bool chmax(T& a, T b){if(a < b){a = b; return true;} return false;}
using ll = long long;

//Konishii

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    while(true) {
        int n; cin >> n;
        if(n == 0) break;

        vector<set<int>> c(n);
        rep(i, n) {
            int a, b; cin >> a >> b;
            c[i].insert(a);
            c[i].insert(b);
            if(a == b) c[i].clear();
        }

        int ans = 0;
        rep(_, n) {
        rep(i, n) {
            if(c[i].size()) {
                int idx = (i + 1) % n;
                while(c[idx].empty()) idx = (idx + 1) % n;
                int x = *c[i].begin();
                if(c[idx].find(x) != c[idx].end()) {
                    c[idx].erase(x);
                } else {
                    c[idx].insert(x);
                }
                c[i].erase(x);

                ans++;
            }
        }
    }
        cout << ans << "\n";
    }   
}
accuracy: 1
time_ms: 20
memory_kb: 3712
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
int main(){
    int n;
    vector<int> lastans;
    while(true){
        cin >> n;
        if(n==0){
            break;
        }
        int c1,c2;
        vector<int> vec(n);
        vector<set<int>> st(n);
        int count=0,ans=0,last=-1,start;
        for(int i=0;i<n;i++){
            cin >> c1 >> c2;
            if(c1!=c2){
                st[i].insert(c1);
                st[i].insert(c2);
                count++;
                if(last!=-1){
                    vec[last]=i;
                }else{
                    start=i;
                }
                last=i;
            }
        }
        if(last!=-1){
            vec[last]=start;
        }
        int i=start,j;
        while(count>0){
            if(st[i].size()==0){
                vec[j]=vec[i];
                i=vec[i];
                continue;
            }
            int p=*st[i].begin();
            st[i].erase(p);
            if(st[i].size()==0){
                vec[j]=vec[i];
            }
            if(st[vec[i]].count(p)){
                st[vec[i]].erase(p);
                count--;
            }else{
                st[vec[i]].insert(p);
            }
            ans++;
            if(st[i].size()!=0){
                j=i;
            }
            i=vec[i];
        }
        lastans.push_back(ans);
    }
    for(auto at:lastans){
        cout << at << endl;
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3596
final_rank: 9

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(ll i=0;i<ll(n);i++)
#define rep2(i,m,n) for(ll i=ll(m);i<ll(n);i++)
using vl = vector<ll>;
using vvl = vector<vl>;
using vvvl = vector<vvl>;
using pl = pair<ll,ll>;
using vpl = vector<pl>;
using vvpl = vector<vpl>;
#define pb push_back

const long double EPS = 0.0000000001;
const ll INF = 1000000000000000000;
const double pi = std::acos(-1.0);

__int128 read_int128(){ //__int128を入力する
    string S;
    cin >> S;
    int N = S.size();
    int st = 0;
    bool minus = false;
    if(S[0] == '-'){
        minus = true;
        st = 1;
    }
    __int128 res = 0;
    rep2(i,st,N) res = res*10+int(S[i]-'0');
    if(minus) res *= -1;
    return res;
}

std::ostream &operator<<(std::ostream &dest, __int128_t value) { //これでcoutで__int128を出力できるように
    std::ostream::sentry s(dest);
    if (s) {
      __uint128_t tmp = value < 0 ? -value : value;
      char buffer[128];
      char *d = std::end(buffer);
      do {
          --d;
          *d = "0123456789"[tmp % 10];
          tmp /= 10;
      } while (tmp != 0);
      if (value < 0) {
          --d;
          *d = '-';
      }
      int len = std::end(buffer) - d;
      if (dest.rdbuf()->sputn(d, len) != len) {
          dest.setstate(std::ios_base::badbit);
      }
    }
    return dest;
}

void Yes(){ cout << "Yes" << endl; } //文字列"Yes"を標準出力
void No(){ cout << "No" << endl; } //文字列"No"を標準出力

template<class T> bool chmin(T& a,T b){
    if(a > b){
        a = b;
        return true;
    }
    else return false;
}

template<class T> bool chmax(T& a,T b){
    if(a < b){
        a = b;
        return true;
    }
    else return false;
}



int main(){
    while(1){
        int N;
        cin >> N;
        if(N == 0) break;
        vvl card(N,vl(2));
        rep(i,N) rep(j,2) cin >> card[i][j];
        int res = 2*N;
        rep(i,N){
            if(card[i][0] == card[i][1]){
                card[i].pop_back();
                card[i].pop_back();
                res -= 2;
            }
        }
        int ans = 0;
        int p = 0;
        while(res > 0){
            ans++;
            while(1){
                if(card[p].size() == 0) p++;
                else break;
                p %= N;
            }
            int p_next = p+1;
            while(1){
                p_next %= N;
                if(card[p_next].size() == 0) p_next++;
                else break;
            }
            sort(card[p].rbegin(),card[p].rend());
            card[p_next].push_back(card[p].back());
            card[p].pop_back();
            rep(i,card[p_next].size()-1){
                bool br = false;
                rep2(j,i+1,card[p_next].size()){
                    if(card[p_next][i] == card[p_next][j]){
                        res -= 2;
                        card[p_next][i] = N+1;
                        card[p_next][j] = N+1;
                        sort(card[p_next].begin(),card[p_next].end());
                        while(card[p_next].size() > 0){
                            if(card[p_next].back() == N+1) card[p_next].pop_back();
                            else break;
                        }
                        br = true;
                        break;
                    }
                }
                if(br) break;
            }
            p = p_next;
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3320
final_rank: 1

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef __int128 lll;
using ull = unsigned long long;
typedef pair<ll,ll> pll;
typedef vector<ll> vll;
typedef vector<pll> vpll;
template<class T> using pqmin = priority_queue<T, vector<T>, greater<T>>;
template<class T> using pqmax = priority_queue<T>;
const ll inf=LLONG_MAX/3;
const ll dx[] = {0, 1, 0, -1, 1, -1, 1, -1};
const ll dy[] = {1, 0, -1, 0, 1, 1, -1, -1};
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define si(x) ll(x.size())
#define rept(n) for(ll _ovo_=0;_ovo_<n;_ovo_++)
#define rep(i,n) for(ll i=0;i<n;i++)
#define per(i,n) for(ll i=n-1;i>=0;i--)
#define rng(i,l,r) for(ll i=l;i<r;i++)
#define gnr(i,l,r) for(ll i=r-1;i>=l;i--)
#define fore(i, a) for(auto &&i : a)
#define fore2(a, b, v) for(auto &&[a, b] : v)
#define fore3(a, b, c, v) for(auto &&[a, b, c] : v)
template<class T> bool chmin(T& a, const T& b){ if(a <= b) return 0; a = b; return 1; }
template<class T> bool chmax(T& a, const T& b){ if(a >= b) return 0; a = b; return 1; }
template<class T, class U> bool chmin(T& a, const U& b){ return chmin(a, (T)b); }
template<class T, class U> bool chmax(T& a, const U& b){ return chmax(a, (T)b); }
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define vec(type,name,...) vector<type>name(__VA_ARGS__)
#define VEC(type,name,size) vector<type>name(size);in(name)
#define VLL(name,size) vector<ll>name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>> name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,w) vector<vector<type>> name(h,vector<type>(w));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>> name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
#define SUM(...) accumulate(all(__VA_ARGS__),0LL)
template<class T> auto min(const T& a){ return *min_element(all(a)); }
template<class T> auto max(const T& a){ return *max_element(all(a)); }
template<class T, class F = less<>> void sor(T& a, F b = F{}){ sort(all(a), b); }
template<class T> void uniq(T& a){ sor(a); a.erase(unique(all(a)), end(a)); }
template<class T, class F = less<>> map<T,vector<ll> > ivm(vector<T>& a, F b = F{}){ map<T,vector<ll> > ret; rep(i,si(a))ret[a[i]].push_back(i); return ret;}
template<class T, class F = less<>> map<T,ll> ivc(vector<T>& a, F b = F{}){ map<T,ll> ret; rep(i,si(a))ret[a[i]]++; return ret;}
template<class T, class F = less<>> vector<T> ivp(vector<T> a){ vector<ll> ret(si(a)); rep(i,si(a))ret[a[i]] = i; return ret;}
template<class T, class F = less<>> vector<ll> rev(vector<T> a){ reverse(all(a)); return a;}
template<class T, class F = less<>> vector<ll> sortby(vector<T> a, F b = F{}){vector<ll> w = a; sor(w,b); vector<pll> v; rep(i,si(a))v.eb(a[i],i); sor(v); if(w[0] != v[0].first)reverse(all(v)); vector<ll> ret; rep(i,si(v))ret.pb(v[i].second); return ret;}
template<class T, class P> vector<T> filter(vector<T> a,P f){vector<T> ret;rep(i,si(a)){if(f(a[i]))ret.pb(a[i]);}return ret;}
template<class T, class P> vector<ll> filter_id(vector<T> a,P f){vector<ll> ret;rep(i,si(a)){if(f(a[i]))ret.pb(i);}return ret;}
ll monotone_left(function<bool(ll)> f){ll l = -1,r = (ll)1e18 + 1; assert(f(l + 1) >= f(r - 1)); while(l + 1 < r){ll mid = (l + r)>> 1; (f(mid)?l:r) = mid;} return l;}
ll monotone_left(ll l,ll r,function<bool(ll)> f){l--; assert(f(l + 1) >= f(r - 1)); while(l + 1 < r){ll mid = (l + r)>> 1; (f(mid)?l:r) = mid;} return l;}
ll monotone_right(function<bool(ll)> f){ll l = -1,r = (ll)1e18 + 1; assert(f(l + 1) <= f(r - 1)); while(l + 1 < r){ll mid = (l + r)>> 1; (f(mid)?r:l) = mid;} return r;}
ll monotone_right(ll l,ll r,function<bool(ll)> f){l--; assert(f(l + 1) <= f(r - 1)); while(l + 1 < r){ll mid = (l + r)>> 1; (f(mid)?r:l) = mid;} return r;}
double monotone_double_left(double l,double r,function<bool(double)> f){assert(f(l) >= f(r)); rep(_,100){double mid = (l + r) / 2.0; (f(mid)?l:r) = mid;} return l;}
double monotone_double_right(double l,double r,function<bool(double)> f){assert(f(l) <= f(r)); rep(_,100){double mid = (l + r) / 2.0; (f(mid)?l:r) = mid;} return r;}
template<class S> S unimodal_max(ll l,ll r,function<S(ll)> f){while(l + 2 < r){ll m1 = l + (r - l) / 3,m2 = l + (r - l) / 3 * 2; if(f(m1) < f(m2))l = m1; else r = m2;} S ret = f(l); rng(k,l,r + 1)chmax(ret,f(k)); return ret;}
template<class S> S unimodal_min(ll l,ll r,function<S(ll)> f){while(l + 2 < r){ll m1 = l + (r - l) / 3,m2 = l + (r - l) / 3 * 2; if(f(m1) > f(m2))l = m1; else r = m2;} S ret = f(l); rng(k,l,r + 1)chmin(ret,f(k)); return ret;}
vector<pll> neighbor4(ll x,ll y,ll h,ll w){vector<pll> ret;rep(dr,4){ll xx = x + dx[dr],yy = y + dy[dr]; if(0 <= xx && xx < h && 0 <= yy && yy <w)ret.eb(xx,yy);} return ret;};
vector<pll> neighbor8(ll x,ll y,ll h,ll w){vector<pll> ret;rep(dr,8){ll xx = x + dx[dr],yy = y + dy[dr]; if(0 <= xx && xx < h && 0 <= yy && yy <w)ret.eb(xx,yy);} return ret;};

void outb(bool x){cout<<(x?"Yes":"No")<<"\n";}
ll max(int x, ll y) { return max((ll)x, y); }
ll max(ll x, int y) { return max(x, (ll)y); }
int min(int x, ll y) { return min((ll)x, y); }
int min(ll x, int y) { return min(x, (ll)y); }
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define lbg(c, x) distance((c).begin(), lower_bound(all(c), (x), greater{}))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define ubg(c, x) distance((c).begin(), upper_bound(all(c), (x), greater{}))
ll gcd(ll a,ll b){return (b?gcd(b,a%b):a);}
vector<pll> factor(ull x){ vector<pll> ans; for(ull i = 2; i * i <= x; i++) if(x % i == 0){ ans.push_back({i, 1}); while((x /= i) % i == 0) ans.back().second++; } if(x != 1) ans.push_back({x, 1}); return ans; }
vector<ll> divisor(ull x){ vector<ll> ans; for(ull i = 1; i * i <= x; i++) if(x % i == 0) ans.push_back(i); per(i,ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; }
vll prime_table(ll n){vec(ll,isp,n+1,1);vll res;rng(i,2,n+1)if(isp[i]){res.pb(i);for(ll j=i*i;j<=n;j+=i)isp[j]=0;}return res;}
ll powll(lll x,ll y){lll res = 1; while(y){ if(y & 1)res = res * x; x = x * x; y >>= 1;} return res;}
ll powmod(lll x,ll y,lll mod){lll res=1; while(y){ if(y&1)res=res*x%mod; x=x*x%mod; y>>=1;} return res; }
ll modinv(ll a,ll m){ll b=m,u=1,v=0;while(b){ll t=a/b;a-=t*b;swap(a,b);u-=t*v;swap(u,v);}u%=m;if(u<0)u+=m;return u;}

template <class T, class S> pair<T, S> operator-(const pair<T, S> &x) { return pair<T, S>(-x.first, -x.second); }
template <class T, class S> pair<T, S> operator-(const pair<T, S> &x, const pair<T, S> &y) { return pair<T, S>(x.fi - y.fi, x.se - y.se); }
template <class T, class S> pair<T, S> operator+(const pair<T, S> &x, const pair<T, S> &y) { return pair<T, S>(x.fi + y.fi, x.se + y.se); }
template <class T> pair<T, T> operator&(const pair<T, T> &l, const pair<T, T> &r) { return pair<T, T>(max(l.fi, r.fi), min(l.se, r.se)); }
template <class T, class S> pair<T, S> operator+=(pair<T, S> &l, const pair<T, S> &r) { return l = l + r; }
template <class T, class S> pair<T, S> operator-=(pair<T, S> &l, const pair<T, S> &r) { return l = l - r; }
template <class T> bool intersect(const pair<T, T> &l, const pair<T, T> &r) { return (l.se < r.se ? r.fi < l.se : l.fi < r.se); }

template <class T> vector<T> &operator++(vector<T> &v) {
		fore(e, v) e++;
		return v;
}
template <class T> vector<T> operator++(vector<T> &v, int) {
		auto res = v;
		fore(e, v) e++;
		return res;
}
template <class T> vector<T> &operator--(vector<T> &v) {
		fore(e, v) e--;
		return v;
}
template <class T> vector<T> operator--(vector<T> &v, int) {
		auto res = v;
		fore(e, v) e--;
		return res;
}
template <class T> vector<T> &operator+=(vector<T> &l, const vector<T> &r) {
		fore(e, r) l.eb(e);
		return l;
}

template<class... Ts> void in(Ts&... t);
[[maybe_unused]] void print(){}
template<class T, class... Ts> void print(const T& t, const Ts&... ts);
template<class... Ts> void out(const Ts&... ts){ print(ts...); cout << '\n'; }
namespace IO{
#define VOID(a) decltype(void(a))
struct S{ S(){ cin.tie(nullptr)->sync_with_stdio(0); fixed(cout).precision(12); } }S;
template<int I> struct P : P<I-1>{};
template<> struct P<0>{};
template<class T> void i(T& t){ i(t, P<3>{}); }
void i(vector<bool>::reference t, P<3>){ int a; i(a); t = a; }
template<class T> auto i(T& t, P<2>) -> VOID(cin >> t){ cin >> t; }
template<class T> auto i(T& t, P<1>) -> VOID(begin(t)){ for(auto&& x : t) i(x); }
template<class T, size_t... idx> void ituple(T& t, index_sequence<idx...>){ in(get<idx>(t)...); }
template<class T> auto i(T& t, P<0>) -> VOID(tuple_size<T>{}){ ituple(t, make_index_sequence<tuple_size<T>::value>{}); }
template<class T> void o(const T& t){ o(t, P<4>{}); }
template<size_t N> void o(const char (&t)[N], P<4>){ cout << t; }
template<class T, size_t N> void o(const T (&t)[N], P<3>){ o(t[0]); for(size_t i = 1; i < N; i++){ o(' '); o(t[i]); } }
template<class T> auto o(const T& t, P<2>) -> VOID(cout << t){ cout << t; }
template<class T> auto o(const T& t, P<1>) -> VOID(begin(t)){ bool first = 1; for(auto&& x : t) { if(first) first = 0; else o(' '); o(x); } }
template<class T, size_t... idx> void otuple(const T& t, index_sequence<idx...>){ print(get<idx>(t)...); }
template<class T> auto o(T& t, P<0>) -> VOID(tuple_size<T>{}){ otuple(t, make_index_sequence<tuple_size<T>::value>{}); }
#undef VOID
}
#define unpack(a) (void)initializer_list<int>{(a, 0)...}
template<class... Ts> void in(Ts&... t){ unpack(IO::i(t)); }
template<class T, class... Ts> void print(const T& t, const Ts&... ts){ IO::o(t); unpack(IO::o((cout << ' ', ts))); }
#undef unpack
bool solve(){
	ll n;
	cin>>n;
	if(n == 0)return false;
	vector<vll> c(n);
	rep(i,n){
		c[i].resize(2);
		rep(j,2)cin>>c[i][j];
		if(c[i][0] == c[i][1]){
			c[i].pop_back();
			c[i].pop_back();
		}
	}
	ll ans = 0;
	ll p = 0;
	while(si(c[p]) == 0){
		p = (p + 1) % n;
		if(p == 0)break;
	}
	while(1){
		{
			ll q = (p + 1) % n;
			while(si(c[q]) == 0 && p != q){
				q = (q + 1) % n;
			}
			if(p == q)break;
			sort(all(c[p]));
			reverse(all(c[p]));
			ll k = c[p].back();
			c[p].pop_back();
			ans++;
			vll v;
			rep(j,si(c[q])){
				if(c[q][j] != k){
					v.eb(c[q][j]);
				}
			}
			if(si(v) == si(c[q]))c[q].eb(k);
			else c[q] = v;
		}
		{
			ll q = (p + 1) % n;
			while(si(c[q]) == 0 && p != q){
				q = (q + 1) % n;
			}
			if(p == q)break;
			p = q;
		}
	}
	cout<<ans<<endl;
	return true;
}
int main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	while(solve()){}
}
accuracy: 1
time_ms: 60
memory_kb: 3416
final_rank: 4

code_snippet: #include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef std::pair<long long, long long> P;
typedef std::priority_queue<P, std::vector<P>, std::greater<P>> PQ;
typedef std::complex<double> cd;

struct P3 {
    long long first, second, third;
};

struct P3P {
    P first, second, third;
};

struct compP3{
    bool operator()(const P3 &p1,const P3 &p2) const {
        if (p1.first != p2.first) return p1.first < p2.first;
        if (p1.second != p2.second) return p1.second < p2.second;
        else return p1.third < p2.third;
    }
};

struct gcompP3{
    bool operator()(const P3 &p1,const P3 &p2) const {
        if (p1.first != p2.first) return p1.first > p2.first;
        if (p1.second != p2.second) return p1.second > p2.second;
        else return p1.third > p2.third;
    }
};

const double PI = acos(-1.0);

bool ckran(int a, int n) {
    return (a >= 0 && a < n);
}

void yn (bool f) {
    if (f) std::cout << "Yes" << '\n';
    else std::cout << "No" << '\n';
}

long long pplus(P a) {
    return a.first + a.second;
}

long long pminus(P a) {
    return a.first - a.second;
}

long long ptime(P a) {
    return a.first * a.second;
}

long long pdiv(P a) {
    return a.first / a.second;
}

template<typename T, typename U>
bool chmax(T& a, U b) {
    if (a < b) {
        a = b;
        return true;
    } else {
        return false;
    }
}

template<typename T, typename U>
bool chmin(T& a, U b) {
    if (a > b) {
        a = b;
        return true;
    } else {
        return false;
    }
}

template<typename T>
void outspace(std::vector<T> a) {
    int n = a.size();
    for (int i = 0; i < n; ++i) {
        std::cout << a[i];
        if (i != n - 1) std::cout << " ";
        else std::cout << std::endl;
    }
}

void outspace(P a) {
    std::cout << a.first << ' ' << a.second << '\n';
}

template<typename T>
void outendl(std::vector<T> a) {
    int n = a.size();
    for (int i = 0; i < n; ++i) {
        std::cout << a[i] << '\n';
    }
}

std::vector<long long> lltovec(long long n, long long base = 10, long long minsize = -1) {
    std::vector<long long> res;
    while (minsize-- > 0 || n > 0) {
        res.push_back(n % base);
        n /= base;
    }
    // std::reverse(res.begin(), res.end());
    return res;
}

long long vectoll(std::vector<long long> vec, long long base = 10) {
    long long res = 0;
    std::reverse(vec.begin(), vec.end());
    for (auto i : vec) {
        res *= base;
        res += i;
    }
    std::reverse(vec.begin(), vec.end());
    return res;
}

static const long long MOD = 998244353;
static const int MAXN = 1000000;  // 必要に応じて大きく設定

// 階乗・階乗逆元の配列
static long long fact[MAXN+1], invFact[MAXN+1];

// 繰り返し二乗法 (a^b mod M)
long long modpow(long long a, long long b, long long M) {
    long long ret = 1 % M;
    a %= M;
    while (b > 0) {
        if (b & 1) ret = (ret * a) % M;
        a = (a * a) % M;
        b >>= 1;
    }
    return ret;
}

// 前処理: 階乗と逆元のテーブルを作る
void initFactorials() {
    // 階乗テーブル
    fact[0] = 1;
    for (int i = 1; i <= MAXN; i++) {
        fact[i] = fact[i-1] * i % MOD;
    }
    // 階乗逆元テーブル
    invFact[MAXN] = modpow(fact[MAXN], MOD - 2, MOD);  // フェルマーの小定理で逆元を計算
    for (int i = MAXN; i >= 1; i--) {
        invFact[i-1] = invFact[i] * i % MOD;
    }
}

// 組み合わせ数 C(n, r)
long long comb(int n, int r) {
    if (r < 0 || r > n) return 0;
    return fact[n] * invFact[r] % MOD * invFact[n - r] % MOD;
}

int main()
{
    vector<ll> an;
    while (true) {
        int n;
        cin >> n;
        if (n == 0) break;
        vector<set<int>> c(n);
        int cur = -1;
        ll ans = 0;
        ll count = 0;
        for (int i = 0; i < n; ++i) {
            int a, b;
            cin >> a >> b;
            if (a == b) continue;
            c[i].insert(a);
            c[i].insert(b);
            if (cur == -1) cur = i;
            count += 2;
        }
        while (count) {
            int next = cur + 1;
            next %= n;
            while (c[next].size() == 0) {
                next++;
                next %= n;
            }
            int d = *(c[cur].begin());
            c[cur].erase(d);
            ans++;
            cur = next;
            if (c[next].find(d) != c[next].end()) {
                c[next].erase(d);
                count -= 2;
                if (count == 0) break;
                if (c[next].size() == 0) {
                    while (c[cur].size() == 0) {
                        cur++;
                        cur %= n;
                    }
                }
            } else {
                c[next].insert(d);
            }
        }
        an.push_back(ans);
        continue;
    }
    outendl(an);
}
accuracy: 1
time_ms: 30
memory_kb: 3516
final_rank: 5

code_snippet: #include <bits/stdc++.h>
// using namespace std;

int main() {

    while (true) {

        int n;
        std::cin >> n;

        if (n == 0) {
            break;
        }

        std::list<std::set<int>> a;
        for (int i = 0; i < n; ++i) {

            int c1, c2;
            std::cin >> c1 >> c2;

            if (c1 == c2) {
                continue;
            }

            a.push_back({c1, c2});
        }

        int ans = 0;
        for (auto now = a.begin(); not a.empty();) {

            if (now == a.end()) {
                now = a.begin();
            }

            if (now->empty()) {
                now = a.erase(now);
                continue;
            }

            int num = *now->begin();
            now->erase(num);
            ++ans;

            auto next = std::next(now);

            if (next == a.end()) {
                next = a.begin();
            }

            if (next->contains(num)) {
                next->erase(num);
            } else {
                next->insert(num);
            }

            if (now->empty()) {
                now = a.erase(now);
            } else {
                ++now;
            }
        }

        std::cout << ans << std::endl;
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3712
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (a); i < (b); i++)

//  問題文より
//  > 遅かれ早かれゲームは終わる
//  よって素直にシミュレーションすれば良いが実装が大変
//  この実装ではdequeを使って実装しました
//      deque: 先頭/末尾への値の挿入/削除がO(1)で行えるデータ構造
//
//  遅かれ早かれゲームは終わるについて
//  全体のカードの中で値が最小のカードに着目する
//  一周する間に必ず最小のカードは捨てられる
//  よってO(N^2)回の操作でゲームは終わる
int solve() {
    int n;
    cin >> n;
    if (n == 0) return 1;
    //  持っているカード
    //  値の降順で管理する
    deque<vector<int>> que;
    rep(i, 0, n) {
        int a, b;
        cin >> a >> b;
        if (a == b) continue;
        if (a < b) swap(a, b);
        que.push_back(vector{a, b});
    }
    int ans = 0;
    while (!que.empty()) {
        assert(ssize(que) >= 2);
        //  player p
        auto p1 = que.front();
        que.pop_front();
        //  player p'
        auto p2 = que.front();
        que.pop_front();

        ans++;
        //  カードは降順で管理しているので、
        //  最小の要素は最奥
        int card = p1.back();
        p1.pop_back();
        auto it = find(begin(p2), end(p2), card);
        if (it == end(p2)) {
            p2.push_back(card);
            sort(begin(p2), end(p2), greater());
        } else {
            p2.erase(it);
        }

        if (!empty(p1)) {
            que.push_back(p1);
        }
        if (!empty(p2)) {
            que.push_front(p2);
        }
    }
    cout << ans << '\n';
    return 0;
}

int main() {
    while (!solve());
}
accuracy: 1
time_ms: 50
memory_kb: 3584
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
int main(){
    cin.tie(nullptr);
	ios_base::sync_with_stdio(false);
    while (true){
        int n;
        cin >> n;
        if (n == 0) break;
        vector<vector<int>> c(n, vector<int>(2));
        int cnt = n;
        for (int i = 0; i < n; i++){
            cin >> c[i][0] >> c[i][1];
            if (c[i][0] == c[i][1]){
                cnt--;
                c[i].pop_back();
                c[i].pop_back();
            }
        }
        int k = 0, ans = 0, m = -1;
        while (cnt > 0){
            while (c[k % n].empty()){
                k++;
            }
            if (m != -1) c[k % n].push_back(m);
            set<int> st(c[k % n].begin(), c[k % n].end());
            map<int, int> mp;
            for (int i : c[k % n]) mp[i]++;
            for (auto [k, v] : mp){
                if (v == 2){
                    st.erase(k);
                    cnt--;
                }
            }
            if (st.empty()){
                c[k % n].clear();
                m = -1;
                continue;
            }
            m = *st.begin();
            st.erase(m);
            c[k % n] = {st.begin(), st.end()};
            ans++;
            k++;
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 110
memory_kb: 3584
final_rank: 16

code_snippet: #include <bits/stdc++.h>
namespace ranges = std::ranges;
int N;
std::vector<int> C[1010];
int next(int v) {
    assert(0 <= v and v < N);
    for (int i = 0 ; i < N ; i++) if (C[(i + v) % N].size())
        return (i + v) % N;
    return -1;
}
void merge(std::vector<int>& c, int val) {
    auto it = ranges::find(c, val);
    if (it != c.end()) {
        c.erase(it);
    }
    else {
        c.push_back(val);
    }
}
int solve() {
    for (int i = 0 ; i < N ; i++) if (C[i][0] == C[i][1]) {
        C[i].clear();
    }
    int ans = 0, p = next(0);
    while (p != -1) {
        assert(C[p].size());
        int v = next((p + 1)%N);
        assert(C[v].size());
        assert(p != v);
        auto pull = ranges::min_element(C[p]);
        merge(C[v], *pull);
        C[p].erase(pull);
        ans++;
        p = next(v);
    }
    return ans;
}
int main() {
    while (true) {
        std::cin >> N;
        if (N == 0) break;
        for (int i = 0 ; i < N ; i++) {
            C[i] = std::vector<int>(2);
            std::cin >> C[i][0] >> C[i][1];
        }
        std::cout << solve() << '\n';
        std::cout.flush();
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3584
final_rank: 7

code_snippet: #pragma region Macros
#include <bits/stdc++.h>

using namespace std;
using lint = long long;
using ull = unsigned long long;
using ld = long double;
using int128 = __int128_t;
#define all(x) (x).begin(), (x).end()
#define EPS 1e-8
#define uniqv(v) v.erase(unique(all(v)), v.end())
#define OVERLOAD_REP(_1, _2, _3, name, ...) name
#define REP1(i, n) for (auto i = std::decay_t<decltype(n)>{}; (i) != (n); ++(i))
#define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i))
#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)
#define log(x) cout << x << endl
#define logfixed(x) cout << fixed << setprecision(10) << x << endl;
#define logy(bool)         \
  if (bool) {              \
    cout << "Yes" << endl; \
  } else {                 \
    cout << "No" << endl;  \
  }

ostream &operator<<(ostream &dest, __int128_t value) {
  ostream::sentry s(dest);
  if (s) {
    __uint128_t tmp = value < 0 ? -value : value;
    char buffer[128];
    char *d = end(buffer);
    do {
      --d;
      *d = "0123456789"[tmp % 10];
      tmp /= 10;
    } while (tmp != 0);
    if (value < 0) {
      --d;
      *d = '-';
    }
    int len = end(buffer) - d;
    if (dest.rdbuf()->sputn(d, len) != len) {
      dest.setstate(ios_base::badbit);
    }
  }
  return dest;
}

template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (int i = 0; i < (int)v.size(); i++) {
    os << v[i] << (i + 1 != (int)v.size() ? " " : "");
  }
  return os;
}

template <typename T>
ostream &operator<<(ostream &os, const set<T> &set_var) {
  for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
    os << *itr;
    ++itr;
    if (itr != set_var.end()) os << " ";
    itr--;
  }
  return os;
}

template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
  for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
    os << itr->first << " -> " << itr->second << "\n";
  }
  return os;
}

template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &pair_var) {
  os << "(" << pair_var.first << ", " << pair_var.second << ")";
  return os;
}

void out() { cout << '\n'; }
template <class T, class... Ts>
void out(const T &a, const Ts &...b) {
  cout << a;
  (cout << ... << (cout << ' ', b));
  cout << '\n';
}

template <typename T>
istream &operator>>(istream &is, vector<T> &v) {
  for (T &in : v) is >> in;
  return is;
}

inline void in(void) { return; }
template <typename First, typename... Rest>
void in(First &first, Rest &...rest) {
  cin >> first;
  in(rest...);
  return;
}

template <typename T>
bool chmax(T &a, const T &b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T>
bool chmin(T &a, const T &b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}

vector<lint> dx8 = {1, 1, 0, -1, -1, -1, 0, 1};
vector<lint> dy8 = {0, 1, 1, 1, 0, -1, -1, -1};
vector<lint> dx4 = {1, 0, -1, 0};
vector<lint> dy4 = {0, 1, 0, -1};

#pragma endregion

int main() {
  cin.tie(0)->sync_with_stdio(0);
  int n;
  while (1) {
    in(n);
    if (n == 0) break;

    deque<set<int>> q;
    rep(i, n) {
      set<int> s;
      int a, b;
      in(a, b);
      if (a == b) continue;
      s.insert(a);
      s.insert(b);
      q.push_back(s);
    }
    int res = 0;
    while (!q.empty()) {
      set<int> cur = q.front();
      q.pop_front();
      set<int> nex = q.front();
      q.pop_front();
      int min_card = *cur.begin();
      cur.erase(cur.begin());
      res++;
      if (nex.contains(min_card)) {
        nex.erase(min_card);
      } else {
        nex.insert(min_card);
      }

      if (!cur.empty()) q.push_back(cur);
      if (!nex.empty()) q.push_front(nex);
    }
    out(res);
  }
}
accuracy: 1
time_ms: 110
memory_kb: 3712
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (a); i < (b); i++)

int solve() {
    int n;
    cin >> n;
    if (n == 0) return 1;

    deque<vector<int>> que;
    rep(i, 0, n) {
        int a, b;
        cin >> a >> b;
        if (a == b) continue;
        if (a < b) swap(a, b);
        que.push_back(vector{a, b});
    }
    int ans = 0;
    while (!que.empty()) {
        auto p1 = que.front();
        que.pop_front();

        auto p2 = que.front();
        que.pop_front();

        ans++;

        int card = p1.back();
        p1.pop_back();
        auto it = find(begin(p2), end(p2), card);
        if (it == end(p2)) {
            p2.push_back(card);
            sort(begin(p2), end(p2), greater());
        } else {
            p2.erase(it);
        }

        if (!empty(p1)) {
            que.push_back(p1);
        }
        if (!empty(p2)) {
            que.push_front(p2);
        }
    }
    cout << ans << '\n';
    return 0;
}

int main() {
    while (!solve());
}
accuracy: 1
time_ms: 50
memory_kb: 3712
final_rank: 17

code_snippet: #include<bits/stdc++.h>
using namespace std;

void solve(int n){
    deque<set<int>> dq;
    for (int i = 0; i < n; i++){
        int a,b;cin >> a >> b;
        if (a != b){
            set<int> s;
            s.insert(a);s.insert(b);
            dq.push_back(s);
        }
    }

    int ans = 0;

    while(!dq.empty()){
        set<int> s;
        s = dq.front();
        dq.pop_front();

        int mn = *s.begin();

        if (s.size() > 1){
            s.erase(mn);
            dq.push_back(s);
        }

        if (dq.front().count(mn)){
            dq.front().erase(mn);
        }
        else dq.front().insert(mn);
        if (dq.front().size() == 0){
            dq.pop_front();
        }
        ans++;
    }
    cout << ans << endl;
}

int main(){
    int n;cin >> n;
    while(n){
        solve(n);
        cin >> n;
    }
}
accuracy: 1
time_ms: 80
memory_kb: 3496
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;

bool solve() {
    int N;
    cin >> N;
    if (N == 0) return false;
    vector<set<int>> C(N, set<int>{});
    int erase = 0;
    for (int i = 0; i < N; i++) {
        int x, y;
        cin >> x >> y;
        if (x != y) C[i].insert(x), C[i].insert(y);
        else erase += 2;
    }
    int ans = 0;
    for (int p = 0; erase < 2 * N; ) {
        ans++;
        while (C[p].empty()) p = (p == N - 1 ? 0 : p + 1);
        int q = (p == N - 1 ? 0 : p + 1);
        while (C[q].empty()) q = (q == N - 1 ? 0 : q + 1);
        int c = *C[p].begin();
        C[p].erase(C[p].begin());
        auto it = C[q].find(c);
        if (it == C[q].end()) {
            C[q].insert(c);
        } else {
            C[q].erase(it);
            erase += 2;
        }
        p = q;
    }
    cout << ans << '\n';
    return true;
}

int main() {
    while (solve()) {}
}
accuracy: 1
time_ms: 10
memory_kb: 3712
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using a2 = array<ll, 2>;
using a3 = array<ll, 3>;

template <typename A> void chmin(A &l, const A &r) {
    if(r < l)
        l = r;
}
template <typename A> void chmax(A &l, const A &r) {
    if(l < r)
        l = r;
}

ll mod = 998244353;

ll n;
vector<a2> v;
void input() {
    cin >> n;
    v.resize(n);
    for(auto &x : v)
        cin >> x[0] >> x[1];
}

void solve() {
    ll ans = 0;
    ll cnt = 0;
    for(int i = 0; i < n; i++) {
        if(v[i][0] == v[i][1]) {
            v[i] = {0, 0};
            cnt++;
        }
    }


    ll cho = 0, now = 0;
    while(cnt < n) {
        if(cho == 0) {
            if(v[now][0]&&(!v[now][1]||v[now][1]>v[now][0])) {
                swap(cho, v[now][0]);
                ans++;
            } else if(v[now][1]&&(!v[now][0]||v[now][0]>v[now][1])) {
                swap(cho, v[now][1]);
                ans++;
            }
        } else {
            if(v[now][0] == cho) {
                ans += v[now][1] != 0;
                cho = v[now][1];
                v[now][0] = 0;
                v[now][1] = 0;
                cnt++;
            } else if(v[now][1] == cho) {
                ans += v[now][0] != 0;
                cho = v[now][0];
                v[now][0] = 0;
                v[now][1] = 0;
                cnt++;
            } else if(v[now][0]||v[now][1]){
                if(v[now][0] < cho && v[now][0]) {
                    swap(cho, v[now][0]);
                }
                if(v[now][1] < cho && v[now][1]) {
                    swap(cho, v[now][1]);
                }
                ans++;
            }
        }
        now++;
        now %= n;
    }
    cout << ans << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    while(1) {
        input();
        if(n == 0)
            break;
        solve();
    }

    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3364
final_rank: 2

code_snippet: #include <iostream>
#include <vector>
#include <map>
using namespace std;

class People {
private:
    map<long long, long long> p;

public:
    People(long long p1 = 1e9, long long p2 = 1e9) {
        if (p1 != p2) {
            p[p1]++;
            p[p2]++;
        }
    }

    void addCard(int c) {
        p[c]++;
        if (p[c] == 2) p.erase(c);
    }

    int getMin() {
        int res = p.begin()->first;
        p[res]--;
        if (p[res] == 0) p.erase(res);
        return res;
    }

    bool isEmpty() {
        return p.empty();
    }
};

bool isEnd(vector<People>& p) {
    bool res = true;
    for (auto& P : p) {
        if (!P.isEmpty()) res = false;
    }
    return res;
}

int main() {
    int n;
    while (cin >> n, n!=0) {
        int ans = 0;
        vector<People> p(n);
        for (int i = 0; i < n; i++) {
            int c1, c2;
            cin >> c1 >> c2;
            p[i] = People(c1, c2);
        }

        int now = 0, next = 0;

        while (!isEnd(p)) {
            if(p[now].isEmpty()){
                for (int i = 0; i < n; i++) {
                    if (!p[i].isEmpty()) {
                        now = i;
                        break;
                    }
                }
            }
            for (int i = 1; i <= n; i++) {
                if (!p[(i + now) % n].isEmpty()) {
                    next = (i + now) % n;
                    break;
                }
            }
            p[next].addCard(p[now].getMin());
            now = next;
            ans++;
        }

        cout << ans << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 340
memory_kb: 3528
final_rank: 20

code_snippet: #include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include <iomanip>
using namespace std;
using ll = long long;//63bit型整数型
int main(){
while(true){
    ll N;
    cin >> N;
    if(N==0)return 0;
    vector<set<ll>>X(N);
    set<ll>out;
    for(int i = 0;i<N;i++){
        ll a,b;
        cin >> a >> b;
        if(a!=b){
        X[i].insert(a);
        X[i].insert(b);
        out.insert(i);
        out.insert(i+N);    
        }
    }
    ll cnt = 0;
    if(out.empty()){
        cout << 0 << "\n";
        continue;
    }
    ll start = *out.lower_bound(0);
    start%=N;
    while(true){
        if(out.empty())break;
        if(X[start].empty()){
            start = *out.lower_bound(start+1);
            start%=N;
            continue;
        }
        ll x = *X[start].begin();
        ll y = *out.lower_bound(start+1);
        y%=N;
        if(X[start].size()==1){
            out.erase(start);
            out.erase(start+N);
        }
        X[start].erase(x);
        if(X[y].count(x)){
            X[y].erase(x);
            if(X[y].empty()){
                out.erase(y);
                out.erase(y+N);
            }
        }
        else X[y].insert(x);
        cnt++;
        start = y;
    }
    cout << cnt << "\n";
}
}
accuracy: 1
time_ms: 50
memory_kb: 3612
final_rank: 11

code_snippet: #include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include <iomanip>
#include <chrono>
#pragma GCC target ("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i,n) for (ll i = 0;i < (ll)(n);i++)
#define Yes cout << "Yes" << "\n"// YESの短縮
#define No cout << "No" << "\n"// NOの短縮
#define rtr0 return(0)//return(0)の短縮
#define gyakugen(x) modpow(x,mod - 2,mod);
#define agyakugen(x) modpow(x,amod - 2,amod);
#define st(A) sort(A.begin(),A.end());
#define rst(A) sort(A.rbegin(),A.rend());
using namespace std;
//using namespace ranges;
using ll = long long;//63bit型整数型
using ld = long double;//doubleよりも長い値を保存できるもの
using ull = unsigned long long;//符号がない64bit型整数
ll mod = 998244353;
ll amod = 1000000007;
ll MINF = -5000000000000000000;
ll INF = 5000000000000000000;
ll inf = 2000000000;
ll minf = -2000000000;
ll BAD = -1;
ll zero = 0;
ld EPS = 1e-10;
vector<ll>randomhash = {(ll)1e9 + 7,(ll)1e9 + 801,((ll)1e8 * 8) + 29,((ll)1e8 * 7) + 159,((ll)1e8 * 9) + 221};
vector<ll>tate = {0,-1,0,1};//グリッド上の全探索時の四方向の上下のチェック
vector<ll>yoko = {1,0,-1,0};//グリッド上の全探索時の四方向の右左のチェック
vector<ll>eightx = {0,-1,-1,-1,0,1,1,1};//グリッド上の全探索時の八方向の上下のチェック
vector<ll>eighty = {1,1,0,-1,-1,-1,0,1};//グリッド上の全探索時の八方向の右左のチェック
vector<ll>hexsax = {0,1,1,0,-1,-1};
vector<ll>hexsay = {1,1,0,-1,-1,0};
//返り値は素数のリスト。
vector < bool > isprime;
vector < ll > Era(int n){//書き方 vector<ll>[] = Era(x); とやるとxまでの素数が出てくる。
	isprime.resize(n, true);
	vector < ll > res;
	isprime[0] = false;
	isprime[1] = false;
	for(ll i = 2; i < n; ++i) isprime[i] = true;
	for(ll i = 2; i < n; ++i) {
		if(isprime[i]) {
			res.push_back(i);
			for(ll j = i * 2; j < n; j += i) isprime[j] = false;
		}
	}
	return res;
}
//　　　　　　素数判定 21~35
ull modmul(ull a,ull b,ull mod) {
    return (__uint128_t)a*b%mod;
}
ll modpow(ll a, ll n, ll mod) {
	ll res = 1;
	while (n > 0) {
		if (n & 1) res = res * a % mod;
		a = a * a % mod;
		n >>= 1;
	}
	return res;
}

long long npow(long long a, long long n){
    long long res = 1;
    while (n > 0) {
		if (n & 1) res = res * a;
		a = a * a;
		n >>= 1;
	}
	return res;
}
//     モッドを使った累乗
long long isqrt(long long num){
    return((long long)sqrtl(num));
}
ld get_theta(ld px,ld py,ld fx,ld fy,ld sx,ld sy){
    ld fxv = fx-px;
    ld fyv = fy-py;
    ld sxv = sx-px;
    ld syv = sy-py;
    ld fsv = fxv*sxv + fyv*syv;
    ld pfs = (ld)sqrt(fxv*fxv+fyv*fyv);
    ld pss = (ld)sqrt(sxv*sxv+syv*syv);
    return acos(fsv/(pfs*pss))*180/M_PI;
};
ld Euclidean_distance(ll x1,ll y1,ll x2,ll y2){
    ld x = abs((ld)x1 - (ld)x2);
    ld y = abs((ld)y1 - (ld)y2);
    return sqrt((x*x) + (y*y));
};
ll Manhattan_distance(ll x1,ll y1,ll x2,ll y2){
    return abs(x1-x2)+abs(y1-y2);
};
void change_bit(ll N,ll start,vector<ll>&X){
    for(ll i = start;i>=0;i--){
        ll a = npow(2,i);
        if(N/a==1){
            X[i]=1;
            N-=a;
        }
    }
}
bool is_in_grid(ll i,ll ii,ll H,ll W){
    bool res = false;
    if(i>=0&&i<H&&ii>=0&&ii<W)res=true;
    return res;
}
template<class T>
struct rolling_hash{
    vector<ull>Power,hash,InvPower;
    ll B = 0;
    ll MOD = 0;
    void set_number(ll base,ll mod){
        B = base;
        MOD = mod;
    }
    void do_hash(const T &S) {
        ll N = S.size();
        Power.resize(N+1);
        InvPower.resize(N+1);
        hash.resize(N+1);
        Power[0] = 1;
        InvPower[0] = 1;
        for (ll i = 0;i<N;i++) {
            Power[i + 1] = modmul(Power[i],B,MOD);
            InvPower[i + 1] = modpow(Power[i+1],MOD-2,MOD);
            hash[i + 1] = (hash[i] + modmul(S[i], Power[i],MOD))%MOD;
        }
    }
    ll get_hash(ll l, ll r) {
        ull res = (hash[r]+MOD-hash[l])%MOD;
        res = modmul(res,InvPower[l],MOD);
        return res;
    }
};
template<class T>
struct combination{
  public:
    vector<T>factorial;
    ll MOD;
    ll N;
    void reset(T n,T mod){
        N = n+1;
        factorial.assign(N,1);
        MOD = mod;
    }
    void calu(){
        for(ll i = 1;i<N;i++){
            factorial[i] = (factorial[i-1]*(i))%MOD;
        }
    }
    T get(T n, T r){
        ll a = factorial[n];
        ll b = (factorial[r]*(factorial[n-r]))%MOD;
        b = modpow(b,MOD - 2,MOD);
        return (a*b)%MOD;
    }
};
template<class T>
struct dijkstra{
  public:
	vector<vector<pair<T,T>>>graph;
	vector<T>ans;
	priority_queue<pair<T,T>,vector<pair<T,T>>,greater<pair<T,T>>>pq;
    void do_dijkstra(T start){//頂点xからダイクストラを行う
		pq.push({0,start});
		ans[start] = 0;
		while(true){
			if(pq.empty())break;
			T cost = pq.top().first;
			T vertex = pq.top().second;
			pq.pop();
            if (cost > ans[vertex]) continue; 
			for(T i = 0;i<graph[vertex].size();i++){
				T nextvertex = graph[vertex][i].first;
				T nextcost = graph[vertex][i].second + cost;
				if(ans[nextvertex] <= nextcost)continue;
					ans[nextvertex] = nextcost;
					pq.push({nextcost,nextvertex});
			}
		}
	}
	void make_indirectedgraph(T u,T v,T cost){//無向辺のグラフ作成
		graph[u].push_back({v,cost});
		graph[v].push_back({u,cost});
	}
	void make_directedgraph(T u,T v,T cost){//有向辺のグラフ作成
		graph[u].push_back({v,cost});
	}
	T output(T end){//答えを出す
		return ans[end];
	} 
	void reset(T N){//リセット
		graph.assign(N, {});
        ans.assign(N, INF);
	}
};
template<class T>
struct unionfind {
public:
    vector<T> parent, rank;
    void reset(T N) { // 初期化
        parent.resize(N);
        rank.assign(N, 1); // 各集合のサイズを 1 にする
        for (T i = 0; i < N; i++) parent[i] = i;
    }
    T leader(T x) { // 経路圧縮による親の取得
        if (parent[x] == x) return x;
        return parent[x] = leader(parent[x]); // 経路圧縮
    }
    void marge(T x, T y) { // ランクによるマージ
        T a = leader(x), b = leader(y);
        if(a!=b){
            if (rank[a] < rank[b]) swap(a, b);
            parent[b] = a;
            rank[a] += rank[b]; // サイズを更新    
        }
    }
    bool same(T x, T y) { // 同じ集合か判定
        return leader(x) == leader(y);
    }
    T size(T x) { // 集合のサイズを取得
        return rank[leader(x)];
    }
    void check(T N) { // デバッグ用: 親の確認
        for (T i = 0; i < N; i++) cout << parent[i] << " ";
        cout << "\n";
    }
};
//セグ木
template <class S, S (*op)(S, S), S (*e)()> struct segtree {
    public:
        segtree() : segtree(0) {}
        segtree(int n) : segtree(std::vector<S>(n, e())) {}
        segtree(const std::vector<S>& v) : _n(int(v.size())){
            log = ceil_pow2(_n);
            size = 1 << log;
            d = std::vector<S>(2 * size, e());
            for (int i = 0; i < _n; i++) d[size + i] = v[i];
            for (int i = size - 1; i >= 1; i--) {
                update(i);
            }
        }
  
        void set(int p, S x) {
            assert(0 <= p && p < _n);
            p += size;
            d[p] = x;
            for (int i = 1; i <= log; i++) update(p >> i);
        }
  
        S get(int p) {
            assert(0 <= p && p < _n);
            return d[p + size];
        }
  
        S prod(int l, int r) {
            assert(0 <= l && l <= r && r <= _n);
            S sml = e(), smr = e();
            l += size;
            r += size;
  
            while (l < r) {
                if (l & 1) sml = op(sml, d[l++]);
                if (r & 1) smr = op(d[--r], smr);
                l >>= 1;
                r >>= 1;
            }
            return op(sml, smr);
        }
  
        S all_prod() { return d[1]; }
  
        template <bool (*f)(S)> int max_right(int l) {
            return max_right(l, [](S x) { return f(x); });
        }
        template <class F> int max_right(int l, F f) {
            assert(0 <= l && l <= _n);
            assert(f(e()));
            if (l == _n) return _n;
            l += size;
            S sm = e();
            do{
                while (l % 2 == 0) l >>= 1;
                if (!f(op(sm, d[l]))) {
                    while (l < size) {
                        l = (2 * l);
                        if (f(op(sm, d[l]))) {
                            sm = op(sm, d[l]);
                            l++;
                        }
                    }
                    return l - size;
                }
                sm = op(sm, d[l]);
                l++;
            }while ((l & -l) != l);
            return _n;
        }
  
        template <bool (*f)(S)> int min_left(int r) {
            return min_left(r, [](S x) { return f(x); });
        }
        template <class F> int min_left(int r, F f) {
            assert(0 <= r && r <= _n);
            assert(f(e()));
            if (r == 0) return 0;
            r += size;
            S sm = e();
            do{
                r--;
                while (r > 1 && (r % 2)) r >>= 1;
                if (!f(op(d[r], sm))) {
                    while (r < size) {
                        r = (2 * r + 1);
                        if (f(op(d[r], sm))) {
                            sm = op(d[r], sm);
                            r--;
                        }
                    }
                    return r + 1 - size;
                }
                sm = op(d[r], sm);
            }while ((r & -r) != r);
            return 0;
        }
  
    private:
        int _n, size, log;
        std::vector<S> d;
  
        void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
        int ceil_pow2(int n) {
            int x = 0;
            while ((1U << x) < (unsigned int)(n)) x++;
            return x;
        }
};

//遅延セグ木
template <class S,S (*op)(S, S),S (*e)(),class F,S (*mapping)(F, S),F (*composition)(F, F),F (*id)()>
struct lazy_segtree {

    public:
        lazy_segtree() : lazy_segtree(0) {}
        lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
        lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {
            log = ceil_pow2(_n);
            size = 1 << log;
            d = std::vector<S>(2 * size, e());
            lz = std::vector<F>(size, id());
            for (int i = 0; i < _n; i++) d[size + i] = v[i];
            for (int i = size - 1; i >= 1; i--) {
                update(i);
            }
        }

    void set(int p, S x) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }

    S get(int p) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        return d[p];
    }

    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return e();

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push(r >> i);
        }

        S sml = e(), smr = e();
        while (l < r) {
            if (l & 1) sml = op(sml, d[l++]);
            if (r & 1) smr = op(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }

        return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    void apply(int p, F f) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = mapping(f, d[p]);
        for (int i = 1; i <= log; i++) update(p >> i);
    }
    void apply(int l, int r, F f) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return;

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        {
            int l2 = l, r2 = r;
            while (l < r) {
                if (l & 1) all_apply(l++, f);
                if (r & 1) all_apply(--r, f);
                l >>= 1;
                r >>= 1;
            }
            l = l2;
            r = r2;
        }

        for (int i = 1; i <= log; i++) {
            if (((l >> i) << i) != l) update(l >> i);
            if (((r >> i) << i) != r) update((r - 1) >> i);
        }
    }

    template <bool (*g)(S)> int max_right(int l) {
        return max_right(l, [](S x) { return g(x); });
    }
    template <class G> int max_right(int l, G g) {
        assert(0 <= l && l <= _n);
        assert(g(e()));
        if (l == _n) return _n;
        l += size;
        for (int i = log; i >= 1; i--) push(l >> i);
        S sm = e();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!g(op(sm, d[l]))) {
                while (l < size) {
                    push(l);
                    l = (2 * l);
                    if (g(op(sm, d[l]))) {
                        sm = op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = op(sm, d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    template <bool (*g)(S)> int min_left(int r) {
        return min_left(r, [](S x) { return g(x); });
    }
    template <class G> int min_left(int r, G g) {
        assert(0 <= r && r <= _n);
        assert(g(e()));
        if (r == 0) return 0;
        r += size;
        for (int i = log; i >= 1; i--) push((r - 1) >> i);
        S sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!g(op(d[r], sm))) {
                while (r < size) {
                    push(r);
                    r = (2 * r + 1);
                    if (g(op(d[r], sm))) {
                        sm = op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

    private:
        int _n, size, log;
        std::vector<S> d;
        std::vector<F> lz;
        int ceil_pow2(int n) {
            int x = 0;
            while ((1U << x) < (unsigned int)(n)) x++;
            return x;
        }
        void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
        void all_apply(int k, F f) {
            d[k] = mapping(f, d[k]);
            if (k < size) lz[k] = composition(f, lz[k]);
        }
        void push(int k) {
            all_apply(2 * k, lz[k]);
            all_apply(2 * k + 1, lz[k]);
            lz[k] = id();
        }
};
struct Euler_Tour{//最小共通祖先,部分木のコスト,通り道のコスト,のグラフを作る部分(オイラーツアー)
    //必要なもの集
    //セグ木は2*Nがベース
    //LCA(最小共通祖先)discovery,finish,visit,high
    //とある頂点xを根とする部分木の範囲 discovery,finish
    //頂点xを根とする部分木の辺と頂点のコストの総和 discovery,finish,vcost1,ecost1
    //頂点xを根とする頂点yまでの最短の辺と頂点のコストの総和 discovery,finish,vcost2,ecost2
    vector<int>discovery,finish,visit,high,vweight,vcost1,vcost2,ecost1,ecost2;
    vector<int>other;
    vector<vector<pair<int,int>>>graph;
    int cnt;
    int othercnt;
    void reset(ll N){
        cnt = 0;
        othercnt = 0;
        other.assign(2*N,0);
        discovery.assign(N,inf);
        finish.assign(N,minf);
        vweight.assign(N,0);
        graph.assign(N,vector<pair<int,int>>(0));
        visit.assign(2*N,0);
        high.assign(2*N,0);
        vcost1.assign(2*N,0);
        vcost2.assign(2*N,0);
        ecost1.assign(2*N,0);
        ecost2.assign(2*N,0);
    };
    void make_graph(ll u,ll v,ll cost){
        if(max(u,v)>graph.size()){
            cout << "not reset or out of range" << "\n";
            return;
        }
        graph[u].push_back({v,cost});
        graph[v].push_back({u,cost});
    }
    void set_vweight(ll vertex,ll cost){
        vweight[vertex]+=cost;
    }
    void DFS(ll vertex,ll nowdepth,ll cost){
        if(discovery[vertex]==inf){
            vcost1[cnt]=vweight[vertex];
            vcost2[cnt]=vweight[vertex];
        }
        else{
            vcost1[cnt]=0;
            vcost2[cnt]=0;
        }
        ecost1[cnt]=cost;
        ecost2[cnt]=cost;
        discovery[vertex]=min(discovery[vertex],cnt);
        visit[cnt]=vertex;
        high[cnt]=nowdepth;
        for(int i = 0;i<graph[vertex].size();i++){
            int x = graph[vertex][i].first;
            int nextcost = graph[vertex][i].second;
            if(discovery[x]!=inf&&graph[vertex].size()==1)othercnt++;
            other[cnt]=othercnt;
            if(discovery[x]==inf){
                cnt++;
                DFS(x,nowdepth+1,nextcost);
                cnt++;
                visit[cnt]=vertex;
                high[cnt]=nowdepth;
                vcost1[cnt]=0;
                ecost1[cnt]=0;
                vcost2[cnt]=vweight[x]*-1;
                ecost2[cnt]=nextcost*-1;
            }
            other[cnt]=othercnt;
        }
        finish[vertex]=cnt+1;
        return;
    }
    int get_size(){
        ll res = high.size()-1;
        return res;
    }
    int get_vcost1(ll i){
        return ecost1[i];
    }
    int get_vcost2(ll i){
        return vcost2[i];
    }
    int get_ecost1(ll i){
        return vcost1[i];
    }
    int get_ecost2(ll i){
        return ecost2[i];
    }
    int get_high(ll i){
        return high[i];
    }
    int get_visit(ll i){
        return visit[i];
    }
    int get_discovery(ll i){
        return discovery[i];
    }
    int get_finish(ll i){
        return finish[i];
    }
};
//遅延セグ木のベース
//型
using segS = ll;
segS oop(segS a,segS b){
    return max(a,b);
}
segS ee(){
    return 0;
}
/*struct segS{
    ll mi = 0;
    ll ma = 0;
};
segS oop(segS a,segS b){
    segS res;
    res.mi = min(a.mi,b.mi);
    res.ma = max(a.ma,b.ma);
    return res;
}
segS ee(){
    segS res;
    res.mi = INF;
    res.ma = MINF;
    return res;
}*/

//using lazyS = ll;
using lazyS = ll;
using lazyF = ll;
lazyS e(){
    lazyS res;
    res = 0;
    return res;
}//範囲外などを起こしてしまったときの返り値
lazyS op(lazyS a, lazyS b){
    lazyS res;
    res = a+b;
    return res; 
}//操作したいこと
lazyS mapping(lazyF f, lazyS x){ 
    x*=f;
    return x; 
}//下まで伝播させたいこと
lazyF composition(lazyF f, lazyF g){ return g *= f; }//まとめてやった場合おこしたいこと
lazyF id(){ return 1; }//遅延セグ木のベース
/*
using lazyS = ll;
using lazyF = ll;
lazyS e(){ return 0;}//範囲外などを起こしてしまったときの返り値
lazyS op(lazyS a, lazyS b){ return a+b; }//操作したいこと
lazyS mapping(lazyF f, lazyS x){ return x /= f; }//下まで伝播させたいこと
lazyF composition(lazyF f, lazyF g){ return g /= f; }//まとめてやった場合おこしたいこと
lazyF id(){ return 1; }//遅延セグ木のベース
*/

int main(){
//B以上は基本詳細を書いておくと便利　A ＝ ooの値とか　見直す時に便利
// この問題の本質
//cout << get_theta(0,0,0,0,0,1) << "\n";
//nCr = A+B+i C B
//nCr = C-i+D-1 C D-1
while(true){
    ll N;
    cin >> N;
    if(N==0)rtr0;
    vector<set<ll>>X(N);
    set<ll>out;
    for(int i = 0;i<N;i++){
        ll a,b;
        cin >> a >> b;
        if(a!=b){
        X[i].insert(a);
        X[i].insert(b);
        out.insert(i);
        out.insert(i+N);    
        }
    }
    ll cnt = 0;
    if(out.empty()){
        cout << 0 << "\n";
        continue;
    }
    ll start = *out.lower_bound(0);
    start%=N;
    while(true){
        if(out.empty())break;
        if(X[start].empty()){
            start = *out.lower_bound(start+1);
            start%=N;
            continue;
        }
        ll x = *X[start].begin();
        ll y = *out.lower_bound(start+1);
        y%=N;
        if(X[start].size()==1){
            out.erase(start);
            out.erase(start+N);
        }
        X[start].erase(x);
        if(X[y].count(x)){
            X[y].erase(x);
            if(X[y].empty()){
                out.erase(y);
                out.erase(y+N);
            }
        }
        else X[y].insert(x);
        cnt++;
        start = y;
        //cout << start <<"\n";
    }
    cout << cnt << "\n";
}
}
accuracy: 1
time_ms: 50
memory_kb: 3620
final_rank: 12

code_snippet: // #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
// #include <atcoder/all>
using namespace std;
// using namespace atcoder;
#define rep(i, a, b) for(int i = (a); i < (b); i++) // [a, b)を昇順に
#define drep(i, a, b) for(int i = (b) - 1; i >= a; i--) // [a, b)を降順に
#define all(v) v.begin(), v.end() // 昇順sortに
#define rall(v) v.rbegin(), v.rend() // 降順sortに
#define sz(x) (int)(x).size()
#define decimal(n) cout << fixed << setprecision(n);
#define debug(x) cerr << #x << " = " << x << endl;
#define Yes cout << "Yes" << endl;
#define No cout << "No" << endl;
#define yesno(condition) { if (condition) cout << "Yes" << endl; else cout << "No" << endl; }
using vi = vector<int>; using vvi = vector<vi>; using vs = vector<string>;
using ll = long long; using vl = vector<ll>; using vvl = vector<vl>; using vvvl = vector<vvl>;
using lll = __int128;
// using mint = modint998244353;
const ll MOD = 998244353;
// using mint = modint;
// const ll MOD = 998244353;
// using mint = modint1000000007;
// const ll MOD = 1000000007;
// using vm = vector<mint>; using vvm = vector<vm>; using vvvm = vector<vvm>;
using P = pair<ll, ll>; using T = tuple<ll, ll, ll>;
using vc = vector<char>;
const ll MAX = 5'000'009; const ll llINF = 2e18;
const int intINF = 2e9; const long double pi = acos(-1);
ll di[] = {0, -1, 0, 1, -1, -1, 1, 1};
ll dj[] = {1, 0, -1, 0, 1, -1, -1, 1};
template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }
template<class T> using pq = priority_queue<T, vector<T>>; //大きい順
template<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>; //小さい順

bool isin(ll i, ll j, ll n, ll m) { return (0 <= i && i < n && 0 <= j && j < m); }
bool is_multipul_overflow(ll a, ll b, ll c) {
    // a * b > cかを判定する
    if (a == 0 || b == 0) return false;
    return (a <= c / b ? false : true);
}

template<class T, size_t n, size_t idx = 0>
auto make_vec(const size_t (&d)[n], const T& init) noexcept {
    if constexpr (idx < n) return std::vector(d[idx], make_vec<T, n, idx + 1>(d, init));
    else return init;
}
template<class T, size_t n>
auto make_vec(const size_t (&d)[n]) noexcept {
    return make_vec(d, T{});
}
/**
 * Read a vector from input. Set start to 1 if you want it to be 1-indexed.
 */
template<typename T>
vector<T> read_vector(int N, int start = 0) {
    vector<T> v(start + N);
    for (int i = start; i < (int)v.size(); i++) {
        std::cin >> v[i];
    }
    return v;
}

void solve(int n) {
    queue<vector<int>> Q;
    rep(i, 0, n) {
        int c1, c2;
        cin >> c1 >> c2;
        if(c1 == c2) continue;
        Q.push({c1, c2});
    }

    auto turn = [&](vector<int> &hand, vector<int> &nexthand) -> void {
        int card = *min_element(all(hand));
        hand.erase(find(all(hand), card));

        auto it = find(all(nexthand), card);
        if(it != nexthand.end()) {
            nexthand.erase(it);
        }
        else nexthand.emplace_back(card);
    };

    int ans = 0;
    while(!Q.empty()) {
        auto hand = Q.front();
        Q.pop();

        auto &nexthand = Q.front();

        turn(hand, nexthand);
        ans++;

        if(!hand.empty()) {
            Q.push(hand);
        }
        if(nexthand.empty()) {
            Q.pop();
        }
    }

    cout << ans << endl;
}

int main() {
    int n;
    while(true) {
        cin >> n;
        if(n == 0) break;
        solve(n);
    }
}
accuracy: 1
time_ms: 40
memory_kb: 3396
final_rank: 3

code_snippet: // AOJ 1657 - Leave No One Behind
// ICPC Japan Domestic Contest 2022 - Problem B
#include <bits/stdc++.h>
using namespace std;

int main() {
    while(true) {
        int N; cin >> N;
        if(N == 0) break;
        vector<set<int>> C(N);
        int win = 0;
        for(int i=0; i<N; ++i) {
            int c1, c2; cin >> c1 >> c2;
            if(c1 == c2) {
                ++win;
            } else {
                C[i].insert(c1);
                C[i].insert(c2);
            }
        }
        if(win == N) {
          cout << 0 << endl;
          continue;
        }

        int turn = 0;
        int i = 0;
        for(; C[i].empty(); ++i) {}
        while(true) {
            ++turn;
            int chosen = *C[i].begin();
            int j = (i+1) % N;
            for(; C[j].empty(); j = (j+1)%N) {}
            if(C[j].count(chosen)) {
                C[j].erase(chosen);
                if(C[j].empty()) {
                    ++win;
                }
            }
            else C[j].insert(chosen);
            C[i].erase(chosen);
            if(C[i].empty()) {
                ++win;
            }
            if(win == N) break;
            i = j;
            for(; C[i].empty(); ++i) {}
        }
        cout << turn << endl;
    }
}
accuracy: 1
time_ms: 30
memory_kb: 3520
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define all(...) std::begin(__VA_ARGS__), std::end(__VA_ARGS__)
#define rall(...) std::rbegin(__VA_ARGS__), std::rend(__VA_ARGS__)
#define OVERLOAD_REP(_1, _2, _3, _4, name, ...) name
#define REP1(n) for(ll i=0;i<(n);i++)
#define REP2(i, n) for (ll i=0;i<(n);i++)
#define REP3(i, a, n) for (ll i=a;i<(n);i++)
#define REP4(i, a, b, n) for(ll i=a;i<(n);i+=b)
#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP4, REP3, REP2, REP1)(__VA_ARGS__)
#define OVERLOAD_RREP(_1, _2, _3, _4, name, ...) name
#define RREP1(n) for(ll i=(n)-1;i>=0;i--)
#define RREP2(i, n) for(ll i=(n)-1;i>=0;i--)
#define RREP3(i, a, n) for(ll i=(n)-1;i>=(a);i--)
#define RREP4(i, a, b, n) for(ll i=(n)-1;i>=(a);i-=(b))
#define rrep(...) OVERLOAD_RREP(__VA_ARGS__, RREP4, RREP3, RREP2, RREP1)(__VA_ARGS__)
#define uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define len(n) (long long)(n).size()
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vs = vector<string>;
using vvs = vector<vs>;
using vvvs = vector<vvs>;
using vld = vector<ld>;
using vvld = vector<vld>;
using vvvld = vector<vvld>;
using vc = vector<char>;
using vvc = vector<vc>;
using vvvc = vector<vvc>;
using pll = pair<ll,ll>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;

ll intpow(ll a,ll b){
    ll ans = 1;
    while (b){
        if (b & 1){
            ans *= a;
        }
        a *= a;
        b /= 2;
    }
    return ans;
}
ll modpow(ll a,ll b,ll c){
    ll ans = 1;
    while (b){
        if (b & 1){
            ans *= a;
            ans %= c;
        }
        a *= a;
        a %= c;
        b /= 2;
    }
    return ans;
}

template<class... T>
void input(T&... a){
    (cin >> ... >> a);
}

#define INT(...) int __VA_ARGS__; input(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define STR(...) string __VA_ARGS__; input(__VA_ARGS__)
#define CHA(...) char __VA_ARGS__; input(__VA_ARGS__)
#define VLL(name,length) vll name(length);rep(i,length){cin >> name[i];}
#define VVLL(name,h,w) vvll name(h,vll(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVLL(name,a,b,c) vvvll name(a,vvll(b,vll(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VI(name,length) vi name(length);rep(i,length){cin >> name[i];}
#define VVI(name,h,w) vvi name(h,vi(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVI(name,a,b,c) vvvi name(a,vvll(b,vi(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VLD(name,length) vld name(length);rep(i,length){cin >> name[i];}
#define VVLD(name,h,w) vvld name(h,vld(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVLD(name,a,b,c) vvvld name(a,vvld(b,vld(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VC(name,length) vc name(length);rep(i,length){cin >> name[i];}
#define VVC(name,h,w) vvc name(h,vc(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVC(name,a,b,c) vvvc name(a,vvc(b,vc(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VS(name,length) vs name(length);rep(i,length){cin >> name[i];}
#define VVS(name,h,w) vvs name(h,vs(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVS(name,a,b,c) vvvs name(a,vvs(b,vs(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define PLL(name) pll name;cin>>name.first>>name.second;
#define VPLL(name,length) vpll name(length);rep(i,length){cin>>name[i].first>>name[i].second;}

void print(){cout << "\n";}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& p) {
    os << "(" << p.first << ", " << p.second << ")";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
    os << "[";
    for (size_t i = 0; i < vec.size(); ++i) {
        os << vec[i];
        if (i + 1 < vec.size()) os << ", ";
    }
    os << "]";
    return os;
}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::vector<std::pair<T1, T2>>& a) {
    os << "[";
    for (size_t j = 0; j < a.size(); ++j) {
        os << "(" << a[j].first << ", " << a[j].second << ")";
		if (j + 1 < a.size()) os << ", ";
    }
	os << "]";
    return os;
}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<std::pair<T1, T2>>>& mat) {
	os << "[";
    for (size_t i = 0; i < mat.size(); ++i) {
		os << "[";
        for (size_t j = 0; j < mat[i].size(); ++j) {
            os << "(" << mat[i][j].first << ", " << mat[i][j].second << ")";
			if (j + 1 < mat[i].size()) os << ", ";
        }
		os << "]";
		if (i + 1 < mat.size()) os << ", ";
    }
	os << "]";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& s) {
    os << "{";
    bool first = true;
    for (const auto& x : s) {
        if (!first) os << ", ";
        os << x;
        first = false;
    }
    os << "}";
    return os;
}

template <typename K, typename V>
std::ostream& operator<<(std::ostream& os, const std::map<K, V>& m) {
    os << "{";
    bool first = true;
    for (const auto& [key, val] : m) {
        if (!first) os << ", ";
        os << key << ": " << val;
        first = false;
    }
    os << "}";
    return os;
}

template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}

void write(){cout << "\n";}
template<class T, class... Ts>
void write(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
void write(vll x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvll x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vi x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvi x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vvvi x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(vld x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvld x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vvvld x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(vc x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvc x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vvvc x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(vs x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvs x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vvvs x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(pll x){cout << x.first << ' ' << x.second << '\n';}
void write(vpll x){rep(i,len(x)){cout << x[i].first << ' ' << x[i].second << '\n';}}
void write(vvpll x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j].first << ' ' << x[i][j].second;if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}

template <typename T>
T sum(const std::vector<T>& v) {
    return std::accumulate(v.begin(), v.end(), T(0));
}

template<class T> bool chmin(T& a, const T& b){ if(a > b){ a = b; return 1; } return 0; }
template<class T> bool chmax(T& a, const T& b){ if(a < b){ a = b; return 1; } return 0; }
template<class T, class U> bool chmin(T& a, const U& b){ if(a > T(b)){ a = b; return 1; } return 0; }
template<class T, class U> bool chmax(T& a, const U& b){ if(a < T(b)){ a = b; return 1; } return 0; }

long long mod_mul(long long a, long long b, long long mod) {
    return (__int128)a * b % mod;
}

long long mod_pow(long long a, long long b, long long mod) {
    long long result = 1;
    a %= mod;
    while (b > 0) {
        if (b & 1) result = mod_mul(result, a, mod);
        a = mod_mul(a, a, mod);
        b >>= 1;
    }
    return result;
}

bool MillerRabin(ll x){
    
    if(x <= 1){return false;}
    if(x == 2){return true;}
    if((x & 1) == 0){return false;}
    vll test;
    if(x < (1 << 30)){
        test = {2, 7, 61};
    } 
    else{
        test = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
    }
    ll s = 0;
    ll d = x - 1;
    while((d & 1) == 0){
        s++;
        d >>= 1;
    }
    for(ll i:test){
        if(x <= i){return true;}
        ll y = mod_pow(i,d,x);
        if(y == 1 || y == x - 1){continue;}
        ll c = 0;
        for(int j=0;j<s-1;j++){
            y = mod_mul(y,y,x);
            if(y == x - 1){
                c = 1;
                break;
            }
        }
        if(c == 0){
            return false;
        }
    }
    return true;
}

#include<atcoder/dsu>

int main(){
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
    while(1){
        LL(n);
        if(n == 0){break;}
        vector<set<ll>> a(n);
        set<ll> s;
        rep(i,n){
            LL(x,y);
            if(x != y){
                a[i].emplace(x);
                a[i].emplace(y);
                s.emplace(i);
                s.emplace(i + n);
            }
        }
        ll ans = 0;
        ll p = n-1;
        while(1){
            if(s.empty()){
                break;
            }
            //rep(i,n){
            //    cout << i << endl;
            //    cout << a[i] << endl;
            //}
            //cout << endl;
            auto y = s.upper_bound(p);
            p = *y;
            p %= n;
            ll q = *(s.upper_bound(p));
            q %= n;
            ll x = *(a[p].begin());
            a[p].erase(a[p].find(x));
            if(a[q].count(x) == 1){
                a[q].erase(a[q].find(x));
            }
            else{
                a[q].emplace(x);
            }
            if(a[p].empty()){
                s.erase(s.find(p));
                s.erase(s.find(p + n));
            }
            if(a[q].empty()){
                s.erase(s.find(q));
                s.erase(s.find(q + n));
            }
            ans++;

        }
        print(ans);
        
        
    }
    
}
accuracy: 1
time_ms: 40
memory_kb: 3840
final_rank: 19