题目
Duizi and Shunzi
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 661 Accepted Submission(s): 311
Problem Description
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.
Input
The input contains several test cases.
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)
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)
Output
For each test case, output the answer in a line.
Sample Input
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
Sample Output
2 4 3 2HintCase 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)
题意
给我们一串数字,让我们从这串数字中找出最多的对子和顺子
解题思路
排一下序,贪心的去利用这些数字,对子需要两个数,顺子需要三个数,所以应该优先贪心对子,这里有一个地方需要优先贪心顺子,就是当顺子已经集齐了两个,这个时候只需要一个数字就可以凑齐顺子,而对子需要两个数字才行
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std ;
const int maxn = 1e6 + 10 ;
int n , a[maxn] ;
int main()
{
while(scanf("%d" , &n) != EOF)
{
for(int i = 0 ; i < n ; i++) scanf("%d" , a + i) ;
sort(a , a + n) ;
int stp = 0 ;
int cnt = 0 ;
int pre = -1 ;
int sum = 0 ;
while(stp < n)
{
// cout<< "stp : " << stp << "cnt : " << cnt << endl ;
if(cnt == 2 && a[stp] == pre + 1)///顺子已经凑齐了两个差一个
{
sum ++ ;
cnt = 0 ;
stp ++ ;
continue ;
}
else if(stp == n - 1)
break ;
else if(a[stp] != a[stp + 1]) ///当前数字和下一个数字不同
{
if(cnt == 0) ///如果顺子个数为0,当前数做顺子的第一个数
{
cnt++ ;
pre = a[stp] ;
stp++ ;
}
else
{
if(a[stp] == pre + 1) ///如果当前数和顺子的前一个数能连续,顺子长度增加,更新顺子当前的数字
{
cnt++ ;
pre = a[stp] ;
stp++ ;
}
else ///如果构不成连续,顺子长度从一重新开始
{
cnt = 1 ;
pre = a[stp] ;
stp++ ;
}
}
}
else if(a[stp] == a[stp + 1])///贪心对子
{
sum++ ;
stp += 2 ;
}
}
printf("%d\n" , sum) ;
}
return 0 ;
}