def find(x):
    if parent[x]==x:
        return x
    else:
        parent[x]=find(parent[x])
        return parent[x]
def union(x,y):
     #global c_c
     xroot=find(x)
     yroot=find(y)
     #print xroot,yroot
     #print size
     if size[xroot]>size[yroot]:
         parent[yroot]=xroot
         #mark[x]=c_c
         #mark[y]=c_c
         size[xroot]+=size[yroot]
     elif size[xroot]<size[yroot]:
         parent[xroot]=yroot
         size[yroot]+=size[xroot]
         #mark[x]=c_c
         #mark[y]=c_c
     elif xroot!=yroot:
         parent[yroot]=xroot
         size[xroot]+=size[yroot]
         #mark[x]=c_c
         #mark[y]=c_c
t=input()
while t!=0:
    n,m=map(int,raw_input().split())
    G=[]
    for _ in xrange(m):
      a,b=map(int,raw_input().split())
      G.append((a,b))
      #G[b].append(a)
    parent=[-1]*(n+1)
    size=[0]*(n+1)
    mark=[-1]*(n+1)
    #costs=map(int,raw_input().split())
    for i in xrange(1,n+1):
      parent[i]=i
      size[i]=1
    c_c=1 
    d={}        
    for i in xrange(m):
        union(G[i][0],G[i][1])
    for i in xrange(1,n+1):
        if find(i)==i:
            d[i]=size[i]
    to=0
    for i in d:
        to=to+d[i]-1
    print to
    t-=1