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.

  ZB正在玩一个纸牌游戏叫做造直道。这幅卡组中的每张卡都有一个1到M间的数字(包括1与M)。一条直道是连续的卡牌序列。值不能循环,因此1不能在M后面。注意除了基本牌外,卡组里还有大小王。每张王可以当成任意一个有效数字(1到M,包括1与M)。

  给你N个整数card[1] .. card[n]表示你的手牌。大小王由0表示,其他牌由他们的值表示。ZB想知道自己手牌可以造出的直道最大长度是多少。

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).

  输入的首行是一个整数T,表示测试样例的数量。

  对于每个测试样例:

  第一行有2个整数N和M(1 <= N, M <= 100000),并且第二行有N个整数card[i] (0 <= card[i] <= M)。

Output

输出

  For each test case, output a single integer in a line -- the longest straight ZB can get.

  对于每个测试样例,输出一行一个整数——ZB可以得到的最大直道长度。

Sample Input - 输入样例

Sample Output - 输出样例

2

7 11

0 6 5 3 0 10 11

8 1000

100 100 100 101 100 99 97 103

5

3

【题解】

  从数据来看,时间复杂度O(N)必定爆炸(反正我没优化出来……),请使用O(NlogN)。

  因此推测出算法,确定左端点(N),二分查(logN)找在鬼牌允许使用范围内的右端点。

  记录当前点前面有多少个0(空缺),然后两端一减就得到需要几张鬼牌填充了。

【代码 C++】

  空间比较任性,速度还能优化……

 #include<cstdio>
#include<cstring>
int data[], sot[];
int length(int L, int R, int i0){//[ L, R]
if (L == R){
if (sot[L] || i0) return ;
return ;
}
int mid = L + R >> ;
if (data[mid] - data[L - ] > i0) return length(L, mid, i0);
return mid - L + + length(mid + , R, i0 - (data[mid] - data[L - ]));
}
int main(){
int T, N, M, i, j, opt;
scanf("%d", &T);
while (T--){
memset(sot, , sizeof(sot));
scanf("%d%d", &N, &M);
for (data[] = i = ; i < N; ++i) scanf("%d", &j), ++sot[j];
for (i = ; i <= M; ++i){
if (sot[i]) data[i] = data[i - ];
else data[i] = data[i - ] + ;
}
for (opt = i = ; i <= M; ++i){
j = length(i, M, sot[]);
if (j>opt) opt = j;
}
printf("%d\n", opt);
}
return ;
}

FZU 2216

05-11 13:17