Problem 2216 The Longest Straight
Accept: 26 Submit: 54
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
ZB is playing a card game where the goal is to make straights. Each card in the deck has a number between 1 and M(including 1 and M). A straight is a sequence of cards with consecutive values. Values do not wrap around, so 1 does not come after M. In addition to regular cards, the deck also contains jokers. Each joker can be used as any valid number (between 1 and M, including 1 and M).
You will be given N integers card[1] .. card[n] referring to the cards in your hand. Jokers are represented by zeros, and other cards are represented by their values. ZB wants to know the number of cards in the longest straight that can be formed using one or more cards from his hand.
Input
The first line contains an integer T, meaning the number of the cases.
For each test case:
The first line there are two integers N and M in the first line (1 <= N, M <= 100000), and the second line contains N integers card[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
Sample Output
5
3
Source
第六届福建省大学生程序设计竞赛-重现赛(感谢承办方华侨大学)
解题思路:
题目大意就是给出一串数字,0代表的是随机的数字,然后找到这一串数字中连续递增的最长数列,数字的顺序是可以打乱的。
所以由题目可以看出数组不是很长所以可以用数组的1或0,来表示这一点上数字的有或无,然后再遍历这个数组,注意0的个数,每次遇到map【x】==0是就用输入的0补上,然后每次找到最大值。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int map[100010];
int max(int x,int y)
{
return x>=y?x:y;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(map,0,sizeof(map));
int N,M,j=0,sum;
scanf("%d%d",&N,&M);
for(int i=0;i<N;i++)
{
scanf("%d",&sum);
if(!sum)
{
j+=1;
}
else
map[sum]=1;
}
int l=1,r=1,c=map[l]==0;//map[l]的值需要判断
int ans=1;
while(r<=M)
{
if(l<r&&c>j)
{
if(map[l]==0)
{
c-=1;
}
l++;
}
else
{
r++;
if(r<=M&&map[r]==0)
{
c++;
}
if(r<=M&&c<=j)
ans=max(ans,r-l+1);
}
}
printf("%d\n",ans);
}
return 0;
}