POJ 1659 (Havel Hakimi theorem, degree sequence reduction undirected graph)

Title Link: http://poj.org/problem?id=1659

Chinese title, needless to say.

Idea: application of havel algorithm:

(1) Sort the sequence from large to small.

(2) Set the maximum degree as t, reduce the T degree after the maximum degree (excluding yourself) by 1 respectively, and then set the maximum degree as 0 (that is, connect the point with the maximum degree with the later points)

(3) If a negative number appears in the sequence, the proof cannot be constructed. If all the sequences change to 0, it can be proved that they can form and jump out of the cycle. If the first two points don't appear, go back to the first step!

Simple example:

4 4 3 3 2 2

0 3 2 2 1 2 after step 2

3 2 2 2 1 0

0 1 1 1 1 0 after step 2

After finishing row 1 1 1 1 0 0

0 0 1 1 0 0 after step 2

After finishing row 1 1 0 0 0 0

0 0 0 0 0 0 0 after step 2

It's all 0. It can form a picture. Jump out!

AC Code:

#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;

struct node{
    int d,id;
}s[15];

int mp[15][15];

bool cmp(node A,node B){
    return A.d > B.d;
}

int main() {
    int t; scanf("%d",&t);
    while(t --){
        memset(mp,0,sizeof(mp));
        int n; scanf("%d",&n);
        for(int i = 1;i <= n;i ++){
            scanf("%d",&s[i].d);
            s[i].id = i;
        }
        int flag = 1;
        while(1){
            sort(s + 1,s + 1 + n,cmp);
            if(s[1].d == 0) break;
            for(int i = 2;i <= 1 + s[1].d;i ++){
                s[i].d --;
                if(s[i].d < 0){ flag = 0; break; }
                mp[s[1].id][s[i].id] = mp[s[i].id][s[1].id] = 1;    //Composition, it's clear that the undirected graph is a symmetric matrix
            }
            s[1].d = 0;
            if(!flag) break;
        }
        if(!flag) printf("NO\n");
        else {
            printf("YES\n");
            for(int i = 1;i <= n;i ++,printf("\n"))
                for(int j = 1;j <= n;j ++)
                    printf("%d ",mp[i][j]);
        }
        printf("\n");
    }
    return 0;
}

 

Posted by therainmaker53 on Sat, 11 Jan 2020 08:17:36 -0800