FZU_2216 The Longest Straight (二分)

来源:互联网 发布:巴丁算法集app 编辑:程序博客网 时间:2024/06/05 06:04
Problem 2216 The Longest Straight

Accept: 441    Submit: 1380
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

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

有n个数,0可以变成1到M之间的任意一个数,求最长能连续的数。

因为m和a【i】的值最大为100000,所以跑数组下标比较方便,然后就是求所有的区间中需要填充的数量,找到数量适合并且区间最长的区间输出。
所以输入的数据要统计0的个数,把输入的每一个值当下标,进行标记,用一个数组来记录到当前值所需要0的个数,下面的难题就是求所有区间所需要的0的个数。

因为m=100000,所以最大区间的端点都已经确定,不妨二分找区间,每次维护最大值,最后输出结果。

二分时令l=i,r=m,如果ans[mid-ans[i]==0的不要返回,此时继续缩小左区间,以便于求的r的最大值,退出二分时的r-i就是以i为左端点,m为右端点,满足0的个数的区间长度,然后维护最大区间长度,得到结果。

时间复杂度 O(mlogm)

代码实现:

#include<iostream>#include<algorithm>#include<cstring>#include<cmath>#include<queue>#include<set>#include<cstdio>#define ll long long#define mset(a,x) memset(a,x,sizeof(a))using namespace std;const double PI=acos(-1);const int inf=0x3f3f3f3f;const double esp=1e-6;const int maxn=1e6+5;const int mod=1e9+7;int dir[4][2]={0,1,1,0,0,-1,-1,0};ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}ll lcm(ll a,ll b){return a/gcd(a,b)*b;}ll inv(ll b){if(b==1)return 1; return (mod-mod/b)*inv(mod%b)%mod;}ll fpow(ll n,ll k){ll r=1;for(;k;k>>=1){if(k&1)r=r*n%mod;n=n*n%mod;}return r;}int map[100005],ans[100005];int main(){int n,m,i,j,k,t,x;scanf("%d",&t);while(t--){scanf("%d%d",&n,&m);mset(map,0);mset(ans,0);int sum=0;for(i=0;i<n;i++){scanf("%d",&x);if(x==0)sum++;elsemap[x]=1;} for(i=1;i<=m;i++){if(map[i])ans[i]=ans[i-1];elseans[i]=(ans[i-1]+1);}int maxx=0;for(i=0;i<=m;i++){int l=i,r=m,mid;while(l<=r){mid=(l+r)/2;if(ans[mid]-ans[i]>sum)r=mid-1;elsel=mid+1;}maxx=max(maxx,r-i);}cout<<maxx<<endl;}return 0;}


原创粉丝点击