ShaysXIA/CodeInsightBench huggingface dataset:
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 1593 ms):
def solve():
    n = int(input())
    d = [{'id': _ + 1, 'v': []} for _ in range(n)]
    for i in range(n - 1):
        u, v = map(int, input().split())
        d[u - 1]['v'].append(v)
        d[v - 1]['v'].append(u)
    if n == 2:
        print(0)
    else:
        for i in range(n):
            s = 0
            for j in d[i]['v']:
                s += len(d[j - 1]['v'])
            d[i]['s'] = s
        d.sort(key=lambda x: (-len(x['v']), x['s']))
        cnt = 1
        cnt += len(d[0]['v']) - 1
        for item in d:
            if d[0]['id'] in item['v']:
                item['v'].remove(d[0]['id'])
        d.remove(d[0])
        d.sort(key=lambda x: (-len(x['v']), x['s']))
        cnt += len(d[0]['v']) - 1
        print(cnt)


for _ in range(int(input())):
    solve()
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 577 ms):
import sys
import math
import collections
import heapq
input=sys.stdin.readline
t=int(input())
for w in range(t):
    n=int(input())
    d={}
    deg=[0 for i in range(n)]
    for i in range(n):
        d[i]=[]
    for i in range(n-1):
        u,v=(int(i) for i in input().split())
        d[u-1].append(v-1)
        d[v-1].append(u-1)
        deg[u-1]+=1
        deg[v-1]+=1
    deg1=[deg[i] for i in range(n)]
    d1={}
    for i in range(n):
        d1[i]=d[i]
    ans=1
    ind,m=-1,-1
    for i in range(n):
        if(deg[i]>m):
            ind=i
            m=deg[i]
    ans+=m-1
    for i in d:
        for j in range(len(d[i])):
            if(d[i][j]==ind):
                del d[i][j]
                deg[i]-=1
                break
    del d[ind]
    del deg[ind]
    ans+=max(deg)-1
    if(deg1.count(m)>1):
        ans1=1
        ind1,m1=-1,-1
        for i in range(n):
            if(deg1[i]>m1 and i!=ind):
                ind1=i
                m1=deg1[i]
        ans1+=m1-1
        for i in d1:
            for j in range(len(d1[i])):
                if(d1[i][j]==ind1):
                    del d1[i][j]
                    deg1[i]-=1
                    break
        del d1[ind1]
        del deg1[ind1]
        ans1+=max(deg1)-1
        ans=max(ans,ans1)
    print(ans)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 1937 ms):
import sys, math, random; from heapq import heapify, heappop, heappush;
from collections import defaultdict, Counter, deque; from bisect import bisect_left, bisect_right
def IL(): return list(map(int, sys.stdin.readline().strip().split()))
def S(): return sys.stdin.readline().strip()

def solve():
    n = IL()[0]
    adj = [[] for _ in range(n + 1)]
    degree = [0] * (n + 1)
    ind = [0] * (n + 1)
    for _ in range(n - 1):
        x, y = IL()
        adj[x].append(y)
        adj[y].append(x)
        degree[x] += 1
        degree[y] += 1
        ind[x] += 1
        ind[y] += 1

    que = deque()
    for node in range(1, n + 1):
        if degree[node] == 1:
            que.append(node)
    val = [-1] * (n + 1)
    level = 0
    while que:
        for _ in range(len(que)):
            node = que.popleft()
            val[node] = level
            for nei in adj[node]:
                ind[nei] -= 1
                if ind[nei] == 1:
                    que.append(nei)
            level += 1
    
    arr = []
    for node in range(1, n + 1):
        arr.append((degree[node], -val[node], node))
    arr.sort()

    ans = 1
    deg, _, first = arr.pop()
    ans += deg - 1
    for nei in adj[first]:
        degree[nei] -= 1
    arr = []
    for node in range(1, n + 1):
        if node != first:
            arr.append((degree[node], -val[node], node))
    arr.sort()
    deg, _, _ = arr.pop()
    ans += deg - 1
    print(ans)

    


    

tt = 1
tt = IL()[0]
for _ in range(tt):
    solve()
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 890 ms):
import heapq




tc = int(input())
for _ in range(0,tc):
  n = int(input())
  
  graph = [[] for i in range(0,n)]
  for i in range(0,n-1):
    inp_arr = [int(i) for i in input().split()]
    v1 = inp_arr[0]-1
    v2 = inp_arr[1]-1
    graph[v1].append(v2)
    graph[v2].append(v1)
  
  edge_count = []
  for i in range(0,n):
    heapq.heappush(edge_count,(-len(graph[i]),i))
  if(n==2):
    print(0)
  else:  
    v1 = heapq.heappop(edge_count)
    v2 = heapq.heappop(edge_count)
    v3 = heapq.heappop(edge_count)
    
    if(v1[0] == v2[0]==v3[0]):
      print(2*-v1[0]-1)
    else:
      
      v1_connections = set()
      for i in range(0,len(graph[v1[1]])):
        v1_connections.add(graph[v1[1]][i])
      
      if(v2[0]!=v3[0]):
        add = -1 if v2[1] in v1_connections else 0
        print(-v1[0]-v2[0]-1+add)
      else: 
        same_cons = [v2[1],v3[1]]
        l = v2[0]
        while(len(edge_count) > 0):
          v = heapq.heappop(edge_count)
          if(v[0] == l):
            same_cons.append(v[1])
          else:
            break
        
        add = -1  
        for v in same_cons:
          if(v not in v1_connections):
            add = 0
            break
        print(-v1[0]-v2[0]-1+add)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 406 ms):
"""
For God so loved the world that he gave his one and only Son, 
that whoever believes in him shall not perish but have eternal life.
JOHN 3:16 
"""
import random
from math import *
from functools import lru_cache
from itertools import accumulate
from fractions import Fraction
from bisect import bisect_left as bl
from bisect import bisect_right as br
from operator import itemgetter
from collections import Counter,deque,defaultdict
from heapq import heappop as hpop, heappush as hpush
# constants
p = 10**9 + 7 
ANS = ['NO','YES']
import sys
input = sys.stdin.readline
output = sys.stdout.write
#sys.setrecursionlimit(110000)
# #For large input
# input = sys.stdin.read
# data = input().split()
# Shortcut for input()
def I(): return int(input())
def S(): return input().strip()
def F(): return float(input())
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LS(): return list(map(str, input().split()))
def LF(): return list(map(float , input().split()))
# Shortcut for output()
res = []
def OI(res): output("\n".join(res))
def OL(res): output("\n".join(" ".join(i) for i in res))






t = I()
for _ in range(t):
    n = I()
    deg = [0]*(n+1)
    g = [[] for _ in range(n+1)]
    for _ in range(n-1):
        u,v = MI()
        deg[u] += 1
        deg[v]+=1
        g[u].append(v)
        g[v].append(u)
    m = max(deg)
    if deg.count(m) >= 3:
        print(2*m-1)
        continue
    ans = m
    node = deg.index(m)
    deg[node] = 0
    for child in g[node]:deg[child]-=1
    ans += (max(deg) - 1)
    print(ans)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 764 ms):
def li():return [int(i)for i in input().split()]
     
for _ in range(int(input())):
    n,=li()
    nv=[0]*(n+1)
    vv=[[]for i in range(n+1)]
    for i in range(n-1):
    	x,y=li()
    	nv[x]+=1
    	vv[x]+=[y]
    	nv[y]+=1
    	vv[y]+=[x]
    m=max(nv)
    if nv.count(m)>=3:print(2*m-1);continue
    node=nv.index(m)
    ans=m
    nv[node]=0
    for e in vv[node]:nv[e]-=1
    ans+=max(nv)-1
    print(ans)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 671 ms):
from sys import stdin
input = stdin.readline

INF = float('inf')
MOD = 1_000_000_007
MOD1 = 998_244_353

from heapq import heappush,heappop
from bisect import bisect_left
from collections import deque

def solve(I):
    n, = map(int,input().strip().split())
    adj = [set() for _ in range(n+1)]
    for _ in range(n-1):
        u,v = map(int,input().strip().split())
        adj[u].add(v)
        adj[v].add(u)

    if n == 2:
        print(0)
        return

    dfs = [(1,0)]
    for v,p in dfs:
        for u in adj[v]:
            if u == p:
                continue
            dfs.append((u,v))

    mx1 = 1
    for v,_ in dfs:
        if len(adj[v]) >= len(adj[mx1]):
            mx1 = v
    
    for v in adj[mx1]:
        adj[v].remove(mx1)
    
    mx2 = 1 if mx1 != 1 else 2
    for v,_ in dfs:
        if v == mx1: continue
        if len(adj[v]) >= len(adj[mx2]):
            mx2 = v

    print(len(adj[mx1]) + len(adj[mx2]) - 1)


        
q = 1
q = int(input().strip())
for i in range(q):
    solve(i+1)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 811 ms):
import sys,math,bisect,heapq
input=sys.stdin.readline
#remember file names are input.txt and output.txt 
#remember to pass only one argument to print
#add this lines before your program and after defining fast io(or that will over write testing)
#after testing done set flag =0
flag=0
if flag:
    class out:
        def __init__(self):
            self.fo=open("cp_with_python/cp/output.txt","w")
        def inu(self,*x):
            if str(type(x))!="<class 'str'>":
                x=str(x)
            self.fo.write(x)
            self.fo.write("\n")
    class inp:
        def __init__(self):
            self.fi=open("cp_with_python/cp/input.txt","r")
        def inu(self):
            return self.fi.readline()
    fy=out()
    print=fy.inu
    fx=inp()
    input=fx.inu

for _ in range(int(input())):
    n=int(input())
    #n,s1,s2=map(int,input().split())
    #a=list(map(int,input().split()))
    graph=[set() for i in range(n)]
    inc=[[i,0] for i in range(n)]
    for i in range(n-1):
        x,y=map(int,input().split())
        graph[x-1].add(y-1)
        graph[y-1].add(x-1)
        inc[x-1][1]+=1
        inc[y-1][1]+=1
    inc.sort(key=lambda x:x[1],reverse=True)
    ans=0
    if n==2:
        print(0)
    else:
        if inc[0][1]==inc[1][1]:
            if inc[0][1]==inc[2][1]:
                print(2*inc[0][1]-1)
            else:
                if inc[1][0] in graph[inc[0][0]]:
                    print(2*inc[0][1]-2)
                else:
                    print(2*inc[0][1]-1)
        else:
            for i in range(1,n):
                if inc[i][1]==inc[1][1]:
                    if inc[i][0] not in graph[inc[0][0]]:
                        print(inc[1][1]+inc[0][1]-1)
                        break
                else:
                    print(inc[0][1]+inc[1][1]-2)
                    break
            else:
                print(inc[0][1]+inc[1][1]-2)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 781 ms):
t = int(input())

for x in range(t):
    n = int(input())
    edges = []
    adj_list = []

    for y in range(n+1):
        adj_list.append([])

    for e in range(n-1):
        a,b = list(map(int, input().split(" ")))
        
        adj_list[a].append(b)
        adj_list[b].append(a)


    for i in range(2):
        cnt_max_edges = 0
        max_edges = []
        for node in range(1, n+1):
            if adj_list[node] != None:
                if len(adj_list[node]) > cnt_max_edges:
                    cnt_max_edges = len(adj_list[node])
                    max_edges = [node]
                elif len(adj_list[node]) == cnt_max_edges:
                    max_edges.append(node)


        if len(max_edges) <= 2 or i == 1:
            max_edges = [max_edges[0]]
        else:
            f = False
            for idx1 in range(0, len(max_edges)):
                if f: break
                for idx2 in range(idx1+1, len(max_edges)):
                    if not max_edges[idx2] in adj_list[max_edges[idx1]]:
                        max_edges = [max_edges[idx1], max_edges[idx2]]
                        f = True
                        break


        for most_edges_node in max_edges:
            for node in adj_list[most_edges_node]:
                adj_list[node].remove(most_edges_node)

            adj_list[most_edges_node] = None

        if len(max_edges) >= 2:
            break

    count_cc = 0
    connected = {}
    v = 1
    for node in range(1, n+1):
        if adj_list[node] != None and not node in connected:
            queue = [node]

            while len(queue) > 0:
                curr = queue.pop()
                connected[curr] = count_cc
                for adj_node in adj_list[curr]:
                    if not adj_node in connected:
                        queue.append(adj_node)
                        connected[adj_node] = count_cc

            count_cc += 1

    print(count_cc)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 718 ms):
import sys, math, collections, bisect, heapq, functools, itertools
sys.setrecursionlimit(10 ** 5)
inp = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = 10 ** 20
MX = 10 ** 5 + 10
orda = ord('a')
fmax = lambda x, y: (x if x > y else y)
fmin = lambda x, y: (x if x < y else y)

def solve():
    N = int(inp())
    degree = [0 for _ in range(N + 1)]
    adj = [[] for _ in range(N + 1)]

    for _ in range(N - 1):
        u, v = list(map(int, inp().split()))
        adj[u].append(v)
        adj[v].append(u)
        degree[u] += 1
        degree[v] += 1

    tmp = []

    for node in range(1, N + 1):
        tmp.append((degree[node], node))

    tmp.sort(reverse=True)
    mx = tmp[0][0]
    best = i = 0

    def get_mx_branch(a, d, node):
        a = a[:]
        d = d[:]
        current, current_mx = d[node], 0

        d[node] = 0
        for u in a[node]:
            d[u] -= 1

        for i in range(1, N + 1):
            current_mx = fmax(current_mx, d[i])

        return current + current_mx - 1

    while i < N and tmp[i][0] == mx:
        if i > 1: break
        best = fmax(best, get_mx_branch(adj, degree, tmp[i][1]))
        i += 1

    return best
    
def main():
    for _ in range(int(inp())):
        print(solve())

if __name__ == '__main__':
    main()
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 1374 ms):
from collections import defaultdict

t = int(input())

def find_max_edges(graph):
    max_us = []
    max_n = -1
    for u in graph:
        if len(graph[u]) > max_n:
            max_us, max_n = [u], len(graph[u])
        elif len(graph[u]) == max_n:
            max_us.append(u)
    return max_us, max_n

for _ in range(t):
    g = defaultdict(list)
    g_lengths = defaultdict(int)
    n = int(input())
    for i in range(n - 1):
        u, v = input().split(' ')
        g[u].append(v)
        g[v].append(u)
        g_lengths[u] += 1
        g_lengths[v] += 1

    us, n = find_max_edges(g)
    max_2nd_edges = 0
    for u in us:
        u_adj = set(g[u])
        for node in g_lengths:
            if node == u:
                continue
            max_2nd_edges = max(g_lengths[node] - (1 if node in u_adj else 0), max_2nd_edges)
        if max_2nd_edges == n:
            break

    components = 1
    components += n - 1
    components += max_2nd_edges - 1
    print(components)
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (runtime: 1171 ms):
def solution():
    n = int(input())
    u_v = [list(map(lambda x: int(x)-1, input().split())) for _ in range(n-1)]
    adj = [set() for _ in range(n)]
    for u, v in u_v:
        adj[u].add(v)
        adj[v].add(u)
    _, _, i = max((len(adj[u]), sum(int(len(adj[u]) > len(adj[v])) for v in adj[u]), u) for u in range(n))
    for v in adj[i]:
        adj[v].remove(i)
    j = max((j for j in range(n) if j != i), key=lambda x: len(adj[x]))
    return len(adj[i])+len(adj[j])-1

for _ in range(int(input())):
    print(solution())

Solution 2 (runtime: 765 ms):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def solve646():
    n = int(input())
    e = []
    for _ in range(n-1):
        u, v = map(int, input().split())
        u, v = u-1, v-1
        e.append([u, v])
    final_res = 0
    for _ in range(2):
        adj = [[] for _ in range(n)]
        for u, v in e:
            adj[u].append(v)
            adj[v].append(u)
        rm = [False] * n
        d = [0] * n
        for i in range(n):
            d[i] = len(adj[i])
        for _ in range(2):
            mx = u = -1
            for i in range(n):
                if not rm[i] and mx < d[i]:
                    mx = d[i]
                    u = i
            rm[u] = True
            d[u] = 0
            for v in adj[u]:
                d[v] -= 1
        res = 0
        visited = rm[:]
        def dfs(u):
            visited[u] = True
            q = [u]
            while q:
                u = q.pop()
                for v in adj[u]:
                    if not visited[v]:
                        visited[v] = True
                        q.append(v)
        for i in range(n):
            if not visited[i]:
                dfs(i)
                res += 1
        final_res = max(final_res, res)
        for i, edge in enumerate(e):
            u, v = edge
            e[i] = [n-1-u, n-1-v]
    return final_res

res_test = []
for _ in range(int(input())):
    res_test.append(solve646())
    
sys.stdout.write("\n".join(map(str, res_test))) #output all test