贪心算法解决数列作为顶点度数构造无向图问题

问题描述:

Given a list of n natural numbers d 1 , d 2,...,dn, show how to decide in polynomial
time whether there exists an undirected graph G = (V, E) whose node degrees
are precisely the numbers d 1, d 2, · · · , dn. G should not contain multiple edges
between the same pair of nodes, or “ loop” edges with both endpoints equal to
the same node.

解题思路:

首先将所有的d1,d2,d3…dn进行排列大小。因为无向图的所有点的度数之和为偶数,所以先判断是否为偶数,如果为偶数,则进行下一步判断;如果为奇数,则一定构不成无向图。

若能够构成无向图,则由于所有的点都有度数,所以度数一定满足将所有的点进行连接。

设将d1,d2,d3…dn进行从大到小排序后得到新的序列nd1,nd2,nd3,…ndn,将他们储存到一个数组sort_num[n]里。使sort_num[0]=nd1,sort_num[1]=nd2,…sort_num[n-1]=ndn

1)此时,使第一个元素与排在其后的nd1个点进行连接,此时第一个点达到自己的度数degree,而其后面nd1个点sort[1…(1+nd1-1)]的度数都减少了1

2)然后,对sort[1…(n-1)]的点根据其度数进行重新从大到小排序。对排序后的新序列执行和(1)相同的操作。

重复(2)的操作,直到最后的一个点度数为0,则可以构成无向图;若最后的一个点度数不为0,则无法构成无向图。

pseudo-code:

if((d1+d2++dn)%2=1) return false;

sort( d[] , 0, n );

得到新的数值从大到小的数组序列:sort_num[0(n-1)]

for(i=0;i<n-1;i++)

{

    j=sort_num[i];

    k=i+1;

    while(j--)

    {

        sort_num[k++]--;//后面的j个数的大小都减去1

    }

    sort(sort_num,i+1,n-1);//重新排列余下的数

}

if(sort_num[0]!=0)

    return false;

else

    return true;

Prove the correctness of your algorithm.

   Sample

   5  3  3  3  2  2à2  2  2  1  1à1  1  1  1à1  1à0

   因此,可以构成无向图。

complexity of your algorithm:

   虽然排序的时间复杂度可以为onlgn,但这里使用了for嵌套while,因此时间复杂度为:o(n^2).



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值