您的位置:首页 > 其它

Graph Construction uva+贪心+Havel-Hakimi定理

2014-07-17 23:01 246 查看
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

解决方案:解本题如果知道Havel-Hakimi定理的话,那就更快了。解决步骤为,每次都拿度最大的那个点连向其它点,若连过之后,其它点的度为负,或最大的点得度大于或等于所有点,都会判为Not possible。本题数据有点弱,用多次调用qsort()都没有超时。

代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#define MMAX 10003
using namespace std;
int p[MMAX];
int n;
int cmp(const void *a ,const void *b){
return *(int*)b-*(int*)a;
}///构造qsort的辅助函数
int main(){
while(~scanf("%d",&n)&&n){
int f=0;
for(int i=0;i<n;i++){
scanf("%d",&p[i]);
}
for(int i=0;i<n;i++){
qsort(&p[i],n-i,sizeof(p[0]),cmp);
if(p[i]>=n-i) {f=1;break;}
if(!p[i]) {break;}
for(int j=i+1;j<=i+p[i];j++){
p[j]--;
if(p[j]<0) {f=1;break;}
}
if(f) break;
}

if(!f)printf("Possible\n");
else printf("Not possible\n");
}

return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: