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 | Possible |
给定每个点的出入度,问是否存在这样的图。
Havel定理,详细见度娘吧。
其实就是贪心的去把最大的分下去。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 10005;
int n, a[maxn], i, j, sum;
bool cmp(const int &a, const int &b){ return a > b; }
bool check()
{
if (sum & 1) return false;
for (i = 0; i < n; i++)
{
sort(a + i, a + n, cmp);
if (i + a[i] >= n || a[i] < 0) return false;
for (j = i + 1; j <= i + a[i]; j++)
{
a[j]--; if (a[j] < 0) return false;
}
}
return true;
}
int main(){
while (cin >> n, n)
{
for (sum = 0, i = 0; i < n; i++) scanf("%d", &a[i]), sum += a[i];
if (check()) printf("Possible\n"); else printf("Not possible\n");
}
return 0;
}