题意:给出每个点的度数,问是否有连边方案使得所有点的度数都满足条件。
思路:Havel-Hakimi定理:令
为有限多个非负整数组成的非递增的点的序列。
可简单图化当且仅当
只含有非负整数且是可简单图化的。
具体求解:
例如度数序列:
- 第一步:删除4,对于第2~5的值均减1
- 再排序
- 第二步:删除3,对于第2到4的值均减1
- 再排序
以此类推,若中途出现负数的值则说明这个序列不可简单图化,若最后结果全为0,则可以简单图化。
#include<cstdio>
#include<iostream>
#include<vector>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
int T;
int n;
struct node
{
int id, x;
bool operator<(const node &b)const
{
return x > b.x;
}
} a[12];
int ma[12][12];
bool Havel_Hakimi()
{
for (int i = 1; i < n; ++i)
{
sort(a + i, a + n + 1);
if (a[i].x + i > n)
return false;
for (int j = i + 1; j <= i + a[i].x; ++j)
{
--a[j].x;
if (a[j].x < 0)
return false;
ma[a[i].id][a[j].id] = ma[a[j].id][a[i].id] = 1;
}
}
return true;
}
int main()
{
cin >> T;
while(T--)
{
cin >> n;
memset(ma, 0, sizeof(ma));
for (int i = 1; i <= n; ++i)
{
a[i].id = i;
cin >> a[i].x;
}
if(Havel_Hakimi())
{
puts("YES");
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
printf("%d ", ma[i][j]);
putchar('\n');
}
}
else
puts("NO");
putchar('\n');
}
return 0;
}