POJ - Frogs' Neighborhood(Havel-Hakimi)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzyws739307453/article/details/86664711

题目链接:http://poj.org/problem?id=1659

Time Limit: 5000MS   Memory Limit: 10000K

Description

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

Input

第一行是测试数据的组数T(0 ≤ T ≤ 20)。每组数据包括两行,第一行是整数N(2 < N < 10),第二行是N个整数,x1, x2,..., 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 

Problem solving report:

Description: 有n个点,给出n个点分别与其它几个点相连,输出他们的相连关系图。
Problem solving: havel-hakimi定理(http://www.docin.com/p-540438846.html)。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct vertex {
    int index;
    int degree;
}v[15];
int n, map[15][15];
bool cmp(struct vertex A, struct vertex B) {
    return A.degree > B.degree;
}
bool Havel() {
    for (int i = 0; i < n - 1; i++) {
        sort(v + i, v + n, cmp);
        int t1 = v[i].index;
        for (int j = i + 1; j <= i + v[i].degree; j++) {
            v[j].degree--;
            if (v[j].degree < 0)
                return false;
            int t2 = v[j].index;
            map[t1][t2] = map[t2][t1] = 1;
        }
    }
    if (v[n - 1].degree)
        return false;
    return true;
}
int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        memset(map, 0, sizeof(map));
        for (int i = 0; i < n; i++) {
            v[i].index = i;
            scanf("%d", &v[i].degree);
        }
        if (Havel()) {
            printf("YES\n");
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++)
                    printf("%d ", map[i][j]);
                printf("\n");
            }
        }
        else printf("NO\n");
        if (t)
            printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lzyws739307453/article/details/86664711
今日推荐