Poj 1659.Frogs' Neighborhood 题解

Description

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

Input

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

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 

Source

POJ Monthly--2004.05.15 Alcyone@pku


思路

给定一个序列,是否可以构建一个图。

经查阅,有Havel-Hakimi定理可用:

  • 非递增排序当前数列\(d[n]\)
  • \(k=d[1]\),将k从数组中移除
  • 从第2个开始的前K个元素都-1
  • 不断重复上述过程直到序列出现负数=不可图全都为0=可图

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cctype>
#include<cstring> 
#include<cstdlib>
using namespace std;
int maps[20][20];
struct node
{
    int id;     //序号
    int degree;     //度
}g[20];
bool cmp(node x,node y)
{
    return x.degree > y.degree;
}
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        memset(maps,0,sizeof(maps));
        memset(g,0,sizeof(g));
        int num;
        cin >> num;
        for(int i=1;i<=num;i++)
        {
            cin >> g[i].degree;
            g[i].id = i;
        }   //读入部分
        
        bool isok = true;
        
        while(true)
        {
            sort(g+1,g+1+num,cmp);
            if(g[1].degree==0)      //说明全都为0了符合条件   
            {
                isok = true;
                break;
            }else                   
            for(int i=2;g[1].degree>0;i++)      //将前k个顶点依次-1
            {
                g[1].degree--;
                g[i].degree--;
                if(g[i].degree<0)
                {
                    isok = false;
                    break;
                }
                maps[g[1].id][g[i].id] = 1;
                maps[g[i].id][g[1].id] = 1;
            }
            if(!isok) break;
        }
        if(isok)
        {
            cout << "YES\n";
            for(int i=1;i<=num;i++)
            {
                for(int j=1;j<=num;j++)
                {
                    cout << maps[i][j] << " ";
                }
                cout << endl;
            }
        }else
            cout << "NO\n";
        cout << endl; 
    }
    return 0;
}

转载于:https://www.cnblogs.com/MartinLwx/p/9737429.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值