# The Longest Straight FZU - 2216 （枚举左端点+二分右端点）

## The Longest Straight

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

code：

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100005;
int n,m,zero;
int sum[maxn];//前缀和用于记录前i个数字中有多少个数字没有
int card[maxn];
int main(){
int t;
scanf("%d",&t);
while(t--){
zero = 0;
memset(sum,0,sizeof(sum));
memset(card,0,sizeof(card));
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++){
int x;
scanf("%d",&x);
if(!x) zero++;
else card[x] = 1;
}
for(int i = 1; i <= m; i++){
sum[i] = sum[i-1] + (!card[i]);//记录没有的牌的个数
}
int ans = 0;
for(int i = 1; i <= m; i++){//枚举左端点
int len = upper_bound(sum + i,sum + 1 + m,zero + sum[i-1]) - (sum + i);
//upper_bound查找第一个大于查找值的位置，所以第一个大于查找值位置减去起始位置恰好就是满足题意的值的长度
//从sum+i开始到sum+1+m最后查找，我们想要找有zero个空缺的一个长度，而因为我们记录的是前缀和是从头开始的，所以我们查找的值实际是zero+之前的sum[i-1]
ans = max(ans,len);
}
printf("%d\n",ans);
}
return 0;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120