POJ-1659 Frogs' Neighborhood

Description

未名湖附近共有N个大小湖泊L1L2, ..., Ln(其中包括未名湖),每个湖泊Li里住着一只青蛙Fi(1 ≤ i ≤ N)。如果湖泊LiLj之间有水路相连,则青蛙FiFj互称为邻居。现在已知每只青蛙的邻居数目x1x2, ..., xn,请你给出每两个湖泊之间的相连关系。

Input

第一行是测试数据的组数T(0 ≤ T ≤ 20)。每组数据包括两行,第一行是整数N(2 < N < 10),第二行是N个整数,x1x2,..., xn(0 ≤ xi ≤ N)。

Output

对输入的每组测试数据,如果不存在可能的相连关系,输出"NO"。否则输出"YES",并用N×N的矩阵表示湖泊间的相邻关系,即如果湖泊i与湖泊j之间有水路相连,则第i行的第j个数字为1,否则为0。每两个数字之间输出一个空格。如果存在多种可能,只需给出一种符合条件的情形。相邻两组测试数据之间输出一个空行。

Sample Input

3
7
4 3 1 5 4 2 1 
6
4 3 1 4 2 0 
6
2 3 1 1 2 1 

Sample Output

YES
0 1 0 1 1 0 1 
1 0 0 1 1 0 0 
0 0 0 1 0 0 0 
1 1 1 0 1 1 0 
1 1 0 1 0 1 0 
0 0 0 1 1 0 0 
1 0 0 0 0 0 0 

NO

YES
0 1 0 0 1 0 
1 0 0 1 1 0 
0 0 0 0 0 1 
0 1 0 0 0 0 
1 1 0 0 0 0 
0 0 1 0 0 0

解题思路:

这道题目其实就是Havel-Hakimi定理的一个简单应用。

Havel-Hakimi定理:由非负数组成的非增序列s:d1,d2,d3,...,dn(n>=2, d1>=1)是可图的,当且仅当序列s1:d2-1,d3-1,d4-1,...,d(d1+1)-1, d(d1+2),...,dn是可图的。

比如说:

给定序列为4 3 1 4 2 0,我们对其按非增序列排序,得到4 4 3 2 1 0,删除首项4,对其后4项每项减1,得到3 2 1 0 0,

对此再排序,再次删除首项,得到序列2 1 -1 0,由于一个图里面的度不可能为负数,所以这个图无法构成图。

而对于能构成图的,每次减去1的点对应的下标与被删去的首项对应的下标构成通路,这道题就解出来了。


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 10 + 3;

typedef struct node{
    int x, id;
    bool operator < (node a){
        return x > a.x;
    }
}Frog;

int flag;
Frog p[maxn];
int nei[maxn][maxn];

int main()
{
    int t, n;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        for(int i = 0; i < n; ++i){
            scanf("%d", &p[i].x);
            p[i].id = i;
        }
        
        sort(p, p + n);
        int flag = 1;
        memset(nei, 0, sizeof(nei));
        for(int i = 0; i < n; ++i){
            for(int j = 1; j <= p[0].x; ++j){
                --p[j].x;
                nei[p[0].id][p[j].id] = 1;
                nei[p[j].id][p[0].id] = 1;
                if(p[j].x < 0) flag = 0;
            }
            p[0].x = 0;
            sort(p, p + n);
        }
        if(flag){
            puts("YES");
            for(int i = 0; i < n; ++i){
                for(int j = 0; j < n; ++j){
                    if(j) printf(" ");
                    printf("%d", nei[i][j]);
                }
                puts("");
            }
        }else puts("NO");
        if(t) puts("");
    }
    return 0;
}



原文地址:https://www.cnblogs.com/wiklvrain/p/8179450.html