fzu 2216 The Longest Straight

来源:互联网 发布:scratch创意编程 pdf 编辑:程序博客网 时间:2024/06/05 13:28

Description

ZB is playing a card game where the goal is tom make straights. Each card in the deck has a number between 1 and M, inclusive. 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, inclusive).

You will be giben 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 <= 10^5), and the second line contains N integers card[i](0 <= card[i] <= M).

Output

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

Sample Input

27 110 6 5 3 0 10 118 1000100 100 100 101 100 99 97 103

Sample Output

53

时间复制度为O(N)

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <algorithm>  
  4. using namespace std;  
  5. const int maxn = 1e5 + 5;  
  6. int card[maxn], num[maxn], pos[maxn];  
  7. int main()  
  8. {  
  9.     int T;  
  10.     scanf("%d", &T);  
  11.     while (T--)  
  12.     {  
  13.         memset(pos, 0, sizeof(pos));  
  14.         memset(num, 0, sizeof(num));  
  15.         memset(card, 0, sizeof(card));  
  16.         int m, n, zero = 0;  
  17.         scanf("%d%d", &m, &n);  
  18.         for (int i = 1; i <= m; i++)  
  19.         {  
  20.             int x;  
  21.             scanf("%d", &x);  
  22.             if (x == 0) zero++;  
  23.             else  
  24.                 card[x] = 1;  
  25.         }  
  26.         int ans = 0,k;  
  27.         pos[0] = 1;  
  28.         for (int i = 1; i <= n; i++)  
  29.         {  
  30.             num[i] = num[i - 1] + (1 - card[i]);  
  31.             if (!card[i])  
  32.                 pos[num[i]] = i;  
  33.             k = num[i] - zero;  
  34.             if (k <= 0)   
  35.             {  
  36.                 ans = i;  
  37.                 continue;  
  38.             }  
  39.             ans = max(ans, i - pos[k]);  
  40.         }  
  41.         printf("%d\n", ans);  
  42.     }  
  43.     return 0;  
  44. }  
  45.   
  46. /* 
  47.  
  48. 22 
  49. 7 11 
  50. 0 6 5 3 0 10 11 
  51. 8 1000 
  52. 100 100 100 101 100 99 97 103 
  53. 3 5 
  54. 1 2 3 
  55. 3 2 
  56. 1 2 3 
  57. 3 5 
  58. 1 2 0 
  59. 3 5 
  60. 2 3 4 
  61. 3 5 
  62. 2 0 4 
  63.  
  64.  
  65. */  

原创粉丝点击