FZU 2216 The Longest Straight 枚举+二分

来源:互联网 发布:淘宝客服招聘上海 编辑:程序博客网 时间:2024/05/16 14:22

 Problem 2216 The Longest Straight

Accept: 267    Submit: 781
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

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

 Sample Output

53

 Source

第六届福建省大学生程序设计竞赛-重现赛(感谢承办方华侨大学)

    题意:给你n张纸牌,代表的数字在1至m区间,给出k张joker可以充当任何牌,现在求出最大的连续区间的长度。

    分析:给定的数字中存在重复,连续的区间是不计算重复的,所以用一个vis数组标记是否存在此个数字。如果使用暴力的话是n*n的复杂度,肯定会炸。该题的关键是joker的处理,可以将joker抽象为将vis数组中0转换成1的次数。使用一个数组记录从开头元素到以下标为结尾的元素区间转化成连续区间需要的joker的个数,即0的个数。此个数的递增的,具有单调性,所以可以考虑二分法求解。

    此题采用枚举加二分的方法,枚举以各个元素为起点,在满足需要的joker数不大于有的joker数的情况下使得区间尽可能的大,使用二分法即可实现,每次更新结果即可得到最终的解。见AC代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=100005;int a[maxn],vis[maxn],dp[maxn];int main(){int T;scanf("%d",&T);while(T--){memset(a,0,sizeof(a));int n,m,j=0,res=0;memset(vis,0,sizeof(vis));memset(dp,0,sizeof(dp));scanf("%d%d",&n,&m);for(int i=1; i<=n; i++){scanf("%d",&a[i]);if(a[i])vis[a[i]]=1;elsej++;}for(int i=1; i<=m; i++){if(vis[i])dp[i]=dp[i-1];elsedp[i]=dp[i-1]+1;}for(int i=0; i<=m; i++){int l=i,r=m,mid;while(l<=r){mid=(l+r)/2;if(dp[mid]-dp[i]>j)//需要的数目 大于  拥有 的数目 则缩小区间r=mid-1;elsel=mid+1;}res=max(res,r-i);}printf("%d\n",res);}}
    刷题长见识……唯有多刷……

    特记下,以备后日回顾。


0 0
原创粉丝点击