Description
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?
Input
The first line contains an integer n — how many numbers Anna had (3 ≤ n ≤ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.
Output
Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).
Sample Input
4 1 2 3 2
YES
6 1 1 2 2 2 3
YES
6 2 4 1 1 2 2
NO
Source
解析
121整体可以把它们看成1。如果x和y是两个相邻数,它们的数目分别是cnt[x],cnt[y](假设cnt[x]>cnt[y])。那么它们等价于cnt[x]-cnt[y]个x.
特殊地,如果某个cnt[x]==cnt[y],直接输出NO,因为它们无论如何也无法被抵消掉。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int N,a[100100],b[100100];
void work()
{
memset(b,0,sizeof(b));
sort(a+1,a+1+N);
int base=a[1]-1; a[1]=1; b[1]++;
for(int i=2;i<=N;i++)
{
a[i]-=base;
if(a[i]-a[i-1]>1) {puts("NO");return;}
b[a[i]]++;
}
bool flag=1;
for(int i=1;i<a[N];i++)
if(b[i] && b[i]<=b[i+1]) b[i+1]-=b[i];
else flag=0;
if(flag && b[a[N]]==0) puts("YES");
else puts("NO");
}
int main()
{
while(scanf("%d",&N)==1)
{
for(int i=1;i<=N;i++) scanf("%d",&a[i]);
work();
}
return 0;
}