Uva--10720(贪心)

2014-07-25 15:00:26

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


思路:贪心,有趣的是:如果按升序排序,每次取最小的数,比如k,就把后面k个数(度数)减一,这样是超时的。
而降序排序,每次取最大的数,比如k,把紧随其后的k个数(度数)减一,这样是过的。借鉴了别人的代码TAT。
 1 /*************************************************************************
 2     > File Name: g.cpp
 3     > Author: Nature
 4     > Mail: 564374850@qq.com
 5     > Created Time: Fri 25 Jul 2014 12:53:38 PM CST
 6 ************************************************************************/
 7 
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cstdlib>
11 #include <iostream>
12 using namespace std;
13 
14 int cmp(const void *a,const void *b){
15     return *(int *)b - *(int *)a;
16 }
17 
18 int n,d[10005];
19 
20 int Work(){
21     int index;
22     for(int i = 0; i < n; ++i){
23         qsort(d + i,n - i,sizeof(int),cmp);
24         if(!d[i]) return 1;
25         if(d[i] >= n) return 0;
26         for(int j = i + 1; j <= d[i] + i; ++j){
27             --d[j];
28             if(d[j] < 0)
29                 return 0;
30         }
31     }
32     return 1;
33 }
34 
35 int main(){
36     while(scanf("%d",&n) == 1 && n){
37         for(int i = 0; i < n; ++i)
38             scanf("%d",&d[i]);
39         if(Work())
40             printf("Possible\n");
41         else
42             printf("Not possible\n");
43     }
44     return 0;
45 }

 

 
 
posted @ 2014-07-25 15:03  Naturain  阅读(162)  评论(0编辑  收藏  举报