2012-04-03 14:40:58Morris

[UVA][Greedy] 10720 - Graph Construction

Problem C

Graph Construction

Time Limit

2 Seconds

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

Output for Sample Input

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

Possible
Not possible
Not possible


Problemsetter: Md. Bahlul Haider
Judge Solution: Mohammed Shamsul Alam
Special thanks to Tanveer Ahsan



做法 : 慢到不行
判定方法就如 Greedy
每次將最多 deg 的點分給最多 deg 的點!如果無法分成功,則 Not possible

#include <stdio.h>
#include <stdlib.h>
int cmp(const void *i, const void *j) {
    return *(int *)j - *(int *)i;
}
int solve(int n, int deg[]) {
    int i, j;
    qsort(deg, n, sizeof(int), cmp);
    for(i = 0; i < n; i++) {
        if(deg[i] > 0) {
            for(j = i+1; j < n; j++) {
                deg[j] --;
                deg[i] --;
                if(deg[j] < 0)        return 0;
                if(deg[i] == 0)        break;
            }
        }
        if(deg[i] != 0)        return 0;
        qsort(deg+i+1, n-i-1, sizeof(int), cmp);
    }
    return 1;
}
int main() {
    int n, deg[10000], i;
    while(scanf("%d", &n) == 1 && n) {
        for(i = 0; i < n; i++)
            scanf("%d", &deg[i]);
        if(solve(n, deg))
            puts("Possible");
        else
            puts("Not possible");
    }
    return 0;
}