Nike likes playing cards and makes a problem of it.
Now give you n integers, ai(1≤i≤n)
We define two identical numbers (eg: 2,2 ) a Duizi,
and three consecutive positive integers (eg: 2,3,4 ) a Shunzi.
Now you want to use these integers to form Shunzi and Duizi as many as possible.
Let s be the total number of the Shunzi and the Duizi you formed.
Try to calculate max(s) .
Each number can be used only once.
Now give you n integers, ai(1≤i≤n)
We define two identical numbers (eg: 2,2 ) a Duizi,
and three consecutive positive integers (eg: 2,3,4 ) a Shunzi.
Now you want to use these integers to form Shunzi and Duizi as many as possible.
Let s be the total number of the Shunzi and the Duizi you formed.
Try to calculate max(s) .
Each number can be used only once.
For each test case, the first line contains one integer n( 1≤n≤106 ).
Then the next line contains n space-separated integers ai ( 1≤ai≤n )
7 1 2 3 4 5 6 7 9 1 1 1 2 2 2 3 3 3 6 2 2 3 3 3 3 6 1 2 3 3 4 5
2
4
3
2
Case 1(1,2,3)(4,5,6) Case 2(1,2,3)(1,1)(2,2)(3,3) Case 3(2,2)(3,3)(3,3) Case 4(1,2,3)(3,4,5)
题意很明确就不说明了,
思路:这是一道简单贪心题,利用下标存储就行了,提前预处理一下前两个值,如果前两个数的个数大于2,直接合成一对,如果第三个数的个数大于2,要考虑前两个数,是否为1,因为要充分利用每个数,比如
1 1 1 2 2 2 3 3 3 利用下标形成的数组是:a[1] = 3 , a[2] = 3 , a[3] = 3;
第一次预处理后:a[1] = 1, a[2] = 1, a[3] = 3; +2
第二次处理后: a[1] = 0, a[2] = 0, a[3] = 2; +1
然后第三次处理:a[1] = 0, a[2] = 0, a[3] = 0; +1
正好是四次,一次这样贪心就行了。代码如下:
#include <stdio.h> #include <string.h> const int maxn = 1000006; int a[maxn]; int t[maxn]; int main() { int n , sum , mx,mn; while(~scanf("%d",&n)) { sum = 0;mx = 0; mn = 9999999; memset(t, 0, sizeof(t)); for(int i = 0; i < n; i++) { scanf("%d",&a[i]); t[a[i]]++; mn = mn>a[i]?a[i]:mn; mx = mx<a[i]?a[i]:mx; } if(t[mn] >= 2) { sum += t[mn]/2; t[mn] %= 2; } if(t[mn+1] >= 2) { sum += t[mn+1]/2; t[mn+1] %= 2; } for(int i = mn+2; i <= mx; i++) { if(t[i] >= 2) { if(t[i-2] == 1 && t[i-1] == 1) { sum++; t[i]--; t[i-1]--; t[i-2]--; i--; } else { sum += t[i]/2; t[i] %= 2; } } else if(t[i] == 1){ if(t[i-2] == 1 && t[i-1] == 1) { sum++; t[i]--; t[i-1]--; t[i-2]--; } } } printf("%d\n",sum); } return 0; }