POJ-1659-Frogs' Neighborhood
链接:
https://vjudge.net/problem/POJ-1659
题意:
未名湖附近共有N个大小湖泊L1, L2, ..., Ln(其中包括未名湖),每个湖泊Li里住着一只青蛙Fi(1 ≤ i ≤ N)。如果湖泊Li和Lj之间有水路相连,则青蛙Fi和Fj互称为邻居。现在已知每只青蛙的邻居数目x1, x2, ..., xn,请你给出每两个湖泊之间的相连关系。
思路:
Havel-Hakimi定理,贪心。
简单来说就是选度最大的,然降序往下连,不过每次要重新排序。
代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
using namespace std;
int Map[20][20];
struct Node
{
int near;
int pos;
bool operator < (const Node & that) const
{
return this->near > that.near;
}
}node[20];
int n;
bool Solve()
{
while (node[1].near != 0)
{
for (int i = 1;i <= node[1].near;i++)
{
node[i+1].near--;
if (node[i+1].near < 0)
return false;
Map[node[1].pos][node[i+1].pos] = 1;
Map[node[i+1].pos][node[1].pos] = 1;
}
node[1].near = 0;
sort(node+1, node+1+n);
}
return true;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
memset(Map, 0, sizeof(Map));
scanf("%d", &n);
for (int i = 1;i <= n;i++)
{
scanf("%d", &node[i].near);
node[i].pos = i;
}
sort(node+1, node+1+n);
if (Solve())
{
printf("YES\n");
for (int i = 1;i <= n;i++)
{
for (int j = 1;j <= n;j++)
printf("%d ", Map[i][j]);
printf("\n");
}
printf("\n");
}
else
printf("NO\n\n");
}
return 0;
}