def dfs(v):
    global mark,c_c
    q=[]
    q.append(v)
    s=1
    while q:
        top=q.pop()
        mark[top]=c_c
        for j in G[top]:
            if mark[j]==-1:
                q.append(j)
                s+=1
                mark[j]=mark[top]
    d[c_c]=s
                
t=input()
while t!=0:
    n,m=map(int,raw_input().split())
    G=[[] for i in xrange(n+1)]
    for k in xrange(m):
        x,y=map(int,raw_input().split())
        G[x].append(y)
        G[y].append(x)
   
    mark=[-1]*(n+1)
    d={}
    c_c=1
    for v in xrange(1,n+1):
       
        if G[v]:
            if mark[v]==-1:
             dfs(v)
             c_c+=1
    n_t=0
    #print d
    for i in d:
        n_t=n_t+d[i]-1
    print n_t
    t-=1