# poj1659-Havel-Hakimi定理

Havel-Hakimi定理:

s:7,6,5,5,2,1,2,1

Frogs’ Neighborhood
Time Limit: 5000MS Memory Limit: 10000K
Total Submissions: 10422 Accepted: 4327 Special Judge
Description

Input

Output

Sample Input

3
7
4 3 1 5 4 2 1
6
4 3 1 4 2 0
6
2 3 1 1 2 1
Sample Output

YES
0 1 0 1 1 0 1
1 0 0 1 1 0 0
0 0 0 1 0 0 0
1 1 1 0 1 1 0
1 1 0 1 0 1 0
0 0 0 1 1 0 0
1 0 0 0 0 0 0

NO

YES
0 1 0 0 1 0
1 0 0 1 1 0
0 0 0 0 0 1
0 1 0 0 0 0
1 1 0 0 0 0
0 0 1 0 0 0
Source

POJ Monthly–2004.05.15 Alcyone@pku
[Submit] [Go Back] [Status] [Discuss]。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=50;
int G[maxn][maxn];
struct jd{
int ds,id;
}v[maxn];
int cmp(struct jd a,struct jd b)
{
return a.ds>b.ds;
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&v[i].ds);
v[i].id=i;
}
int f=1;
memset(G,0,sizeof(G));
for(int i=0;i<n&&f;i++)//对于每一个顶点进行Havel-Hakimi定理判定
{
sort(v+i,v+n,cmp);
int d=v[i].id;
int k=v[i].ds;
if(k>n-i-1){f=0;break;}
for(int j=1;j<=k&&f;j++)
{
int h=v[i+j].id;
if(v[i+j].ds<=0){f=0;break;}
v[i+j].ds--;
G[d][h]=G[h][d]=1;
}
}
if(f){
printf("YES\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(j==n-1)
printf("%d\n",G[i][j]);
else
printf("%d ",G[i][j]);
}
}
}
else
printf("NO\n");
if(t)
printf("\n");
}
return 0;
}


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 50
using namespace std;

struct vertex{
int degree;//度数
int index;//序号
}v[N];
int cmp(const void *a,const void *b)
{
return ((vertex*)b)->degree-((vertex*)a)->degree;
}
int main()
{
int r,k,p,q;
int i,j;
int d1;
int T,n;
int Edge[N][N],flag;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&v[i].degree);
v[i].index=i;
}
memset(Edge,0,sizeof(Edge));
flag=1;
for(k=0;k<n&&flag;k++)
{
qsort(v+k,n-k,sizeof(vertex),cmp);
i=v[k].index;
d1=v[k].degree;
if(d1>n-k-1)flag=0;
for(r=1;r<=d1&&flag;r++)
{
j=v[k+r].index;
if(v[k+r].degree<=0)flag=0;
v[k+r].degree--;
Edge[i][j]=Edge[j][i]=1;
}
}
if(flag)
{
puts("YES");
for(int x=0;x<n;x++)
{
for(int y=0;y<n;y++)
{
if(y)
printf(" ");
printf("%d",Edge[x][y]);
}
printf("\n");
}
}
else
printf("NO\n");
if(T)
printf("\n");
}
return 0;
}