Problem 2216 The Longest Straight
Accept: 178 Submit: 536
Time Limit: 1000 mSec Memory Limit : 32768 KB
ProblemDescription
ZB is playing a card game where the goal is to makestraights. Each card in the deck has a number between 1 and M(including 1 andM). A straight is a sequence of cards with consecutive values. Values do notwrap around, so 1 does not come after M. In addition to regular cards, the deckalso contains jokers. Each joker can be used as any valid number (between 1 andM, including 1 and M).
You will be given N integers card[1] .. card[n] referringto the cards in your hand. Jokers are represented by zeros, and other cards arerepresented by their values. ZB wants to know the number of cards in thelongest straight that can be formed using one or more cards from his hand.
Input
The first line contains an integer T, meaning the numberof the cases.
For each test case:
The first line there are two integers N and M in thefirst line (1 <= N, M <= 100000), and the second line contains N integerscard[i] (0 <= card[i] <= M).
Output
For each test case, output a single integer in a line –the longest straight ZB can get.
Sample Input
2
7 11
0 6 5 3 0 10 11
8 1000
100 100 100 101 100 99 97 103
SampleOutput
5
3
题意:此题是让我们求最大连续子串,而0(即鬼)可以充当任意牌(大于等于1小于等于m)我们可以定义一个数组来统计卡牌是否出现,在定义一个数组来统计达到最大连续子串需要0的个数。然后用二分查找即可。
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int card[100050];//存储数字是否出现
int num[100050];//最长连续子段所需要0的个数
int n,m;
int t;
scanf("%d",&t);
while(t--)
{
int zero = 0;
memset(card,0,sizeof(card));
memset(num,0,sizeof(num));
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++)
{
int a;
scanf("%d",&a);
if(a)
card[a] = 1;
else
zero++;
}
for(int i = 1; i <= m; i++)
{
num[i] = num[i-1] + (1-card[i]);
}
int ans = 0;
for(int i = 1; i <= m; i++)
{
int k = upper_bound(num+i,num+m+1,zero+num[i-1]) - num -i;
ans = max(k,ans);
}
printf("%d\n",ans);
}
return 0;
}