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

Solution 1 (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)

Solution 2 (runtime: 468 ms):
def max1(t) :
    indice=0
    nb=t[0]
    n=len(t)
    for i in range(1,n) :
        if t[i]>nb :
            indice=i
            nb=t[i]
    return nb,indice

def max2(t,j) :
    
    if j==0 :
        indice=1
        nb=t[1]
    
    else:
        nb=t[0]
        indice=0
    n=len(t)
    for i in range(1,n) :
        if i!=j :
            if t[i]>nb :
                indice=i
                nb=t[i]
    return nb,indice

for _ in range(int(input())):
    n=int(input())
    if n<=2 :
        for i in range(n-1):
            u,v=map(int,input().split())
        print(0)
    else:
        t=[0]*n
        t2=[0]*n
        l=[]
        for i in range(n-1):
            u,v=map(int,input().split())
            l.append((u,v))
            t[u-1]+=1
            t[v-1]+=1
            t2[u-1]+=1
            t2[v-1]+=1
        nb1,indice1=max1(t)
        nb3,indice3=max2(t2,indice1)
        t[indice1]=0
        t2[indice3]=0
        for i in l :
            if i[0]-1==indice1 :
                t[i[1]-1]-=1
            elif i[1]-1==indice1 :
                t[i[0]-1]-=1
        for i in l :
            if i[0]-1==indice3 :
                t2[i[1]-1]-=1
            elif i[1]-1==indice3 :
                t2[i[0]-1]-=1
        nb2,indice2=max1(t)
        nb4,indice4=max1(t2)
 
  
        print(max(nb1+nb2-1,nb3+nb4-1))
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (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)

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: 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)

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: 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)

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: 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)

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: 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)

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
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (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)

Solution 2 (runtime: 468 ms):
def max1(t) :
    indice=0
    nb=t[0]
    n=len(t)
    for i in range(1,n) :
        if t[i]>nb :
            indice=i
            nb=t[i]
    return nb,indice

def max2(t,j) :
    
    if j==0 :
        indice=1
        nb=t[1]
    
    else:
        nb=t[0]
        indice=0
    n=len(t)
    for i in range(1,n) :
        if i!=j :
            if t[i]>nb :
                indice=i
                nb=t[i]
    return nb,indice

for _ in range(int(input())):
    n=int(input())
    if n<=2 :
        for i in range(n-1):
            u,v=map(int,input().split())
        print(0)
    else:
        t=[0]*n
        t2=[0]*n
        l=[]
        for i in range(n-1):
            u,v=map(int,input().split())
            l.append((u,v))
            t[u-1]+=1
            t[v-1]+=1
            t2[u-1]+=1
            t2[v-1]+=1
        nb1,indice1=max1(t)
        nb3,indice3=max2(t2,indice1)
        t[indice1]=0
        t2[indice3]=0
        for i in l :
            if i[0]-1==indice1 :
                t[i[1]-1]-=1
            elif i[1]-1==indice1 :
                t[i[0]-1]-=1
        for i in l :
            if i[0]-1==indice3 :
                t2[i[1]-1]-=1
            elif i[1]-1==indice3 :
                t2[i[0]-1]-=1
        nb2,indice2=max1(t)
        nb4,indice4=max1(t2)
 
  
        print(max(nb1+nb2-1,nb3+nb4-1))
Problem: 2063C - Remove Exactly Two
Language: python

Solution 1 (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)

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: 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)

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)