poj 1659 Frogs' Neighborhood

Frogs' Neighborhood
Time Limit: 5000MS   Memory Limit: 10000K
Total Submissions: 5599   Accepted: 2419   Special Judge

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 
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
struct node
{
  int id, deg;
}no[15];
int cmp(const void *a, const void *b){
  return (*(node*)a).deg < (*(node*)b).deg ? 1 : -1;
}
int main(void){
#ifndef ONLINE_JUDGE
  freopen("poj1659.in", "r", stdin);
#endif
  int t; scanf("%d", &t);
  int edge[15][15];
  for (int i = 0; i < t; ++i){
    int n; scanf("%d", &n);
    for (int j = 0; j < n; ++j) {scanf("%d", &no[j].deg); no[j].id = j;}
    memset(edge, 0, sizeof(edge));
    bool flag = true;
    for (int k = 0; k < n && flag; ++k){
      qsort(no+k, n-k, sizeof(node), cmp);
      int r = no[k].id, c;
      if (no[k].deg > n-k-1) flag = false;
      int temp = no[k].deg, s = 1;
      while (temp-- && flag) {
        no[k+s].deg--; c = no[k+s].id;
        if (no[k+s].deg < 0) flag = false;
        else edge[r][c]=edge[c][r]=1;
        s++;
      }
    }
    if (!flag) printf("NO\n");
    else{
      printf("YES\n");
      for (int k = 0; k < n; ++k){
        for (int j = 0; j < n; ++j){ 
          if (j) printf(" "); 
          printf("%d", edge[k][j]);
        }
        printf("\n");
      }
    }
    if (i != t-1) printf("\n");
  }
  return 0;
}

图论,已知点的度数,判断几个点是否可图。

原文地址:https://www.cnblogs.com/liuxueyang/p/2958325.html