UVa 10720 - Graph Construction(Havel-Hakimi定理)

时间:2022-05-20 07:15:55

题目链接: 传送门

Graph Construction

Time Limit: 3000MS     Memory Limit: 65536K

Description

Graph is a collection of edges E and vertices V. Graph has a wide variety of applications in computer. There are different ways to represent graph in computer. It can be represented by adjacency matrix or by adjacency list. There are some other ways to represent graph. One of them is to write the degrees (the numbers of edges that a vertex has) of each vertex. If there are n vertices then n integers can represent that graph. In this problem we are talking about simple graph which does not have same endpoints for more than one edge, and also does not have edges with the same endpoint. Any graph can be represented by n number of integers. But the reverse is not always true. If you are given n integers, you have to find out whether this n numbers can represent the degrees of n vertices of a graph

Input

Each line will start with the number n (≤ 10000). The next n integers will represent the degrees of n vertices of the graph. A ‘0’ input for n will indicate end of input which should not be processed.

Output

If the n integers can represent a graph then print ‘Possible’. Otherwise print ‘Not possible’. Output for each test case should be on separate line.

Sample Input

4 3 3 3 3 6 2 4 5 5 2 1 5 3 2 3 2 1 0

Sample Output

Possible
Not possible
Not possible
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

bool cmp(int x,int y)
{
    return x>y;
}

int main()
{
    int N;
    while (~scanf("%d",&N) && N)
    {
        int ans[10005] = {0};
        bool flag = true;
        for (int i = 0;i < N;i++)
        {
            scanf("%d",&ans[i]);
        }
        while (flag)
        {
            sort(ans,ans+N,cmp);
            int tmp = ans[0];
            if (tmp == 0)
            {
                break;
            }
            for (int i = 1;i <= tmp;i++)
            {
                ans[i]--;
                if (ans[i] < 0)
                {
                    flag = false;
                    break;
                }
            }
            ans[0] = 0;
            if (!flag)
            {
                break;
            }
        }
        if (!flag)
        {
            printf("Not possible\n");
        }
        else
        {
            printf("Possible\n");
        }
    }
    return 0;
}