AC代码(c++)
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
#include <queue>
int main()
{
int st[12000];
queue<int>q;
int t;
cin>>t;
while(t--)
{
memset(st,0,sizeof(st));
int n,m;
cin>>n>>m;
int x,y;
for(int i=1; i<=m; i++)
{
cin>>x>>y;
st[x]++; //每个节点的入度加一
st[y]++;
}
sort(st+1,st+1+n); //对每个节点的入度排序
for(int i=1; i<=n; i++)
{
if(st[i]<2)
q.push(st[i]); //只要入度小于二就压进队列中,因为构成完美图,每个节点的度数都应该大于等于二
}
int a,b,num=0;
while(q.size()>=2)
{
a=q.front(); //从队列中取出两个元素,一条边连接两个顶点
q.pop();
b=q.front();
q.pop();
a++;
b++;
num++;
if(a<2)//如果节点的入度还是小于二,继续压进队列
q.push(a);
if(b<2)
q.push(b);
}
if(q.size()==1) //如果队列中还剩余一个节点,那么条数也要加一
num++;
cout<<num<<endl;
}
return 0;
}