FZU 2216 The Longest Straight (二分)

Problem 2216 The Longest Straight

Accept: 128    Submit: 369
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

题意:求最长有序子串,0可变成1-M的任意数。

思路:统计0的数目,并在vis数组中将有的数字置为1,cnt0数组统计从1到当前数字若要成为有序序列需要补全的数目。从1-M枚举起点的位置,用二分搜索终点的位置。

<strong>#include<iostream>
#include<cstdio>
#include<algorithm>
#include<set>
#include<cmath>
using namespace std;
bool vis[100005];
int cnt0[100005];//从1至当前数补全需要的0数目 
int num0;
int f(int mid,int i){//如果需要补全的数目小于等于拥有的0数目,则返回1. 
	if(cnt0[mid]-cnt0[i-1]<=num0)return 1;
	else return 0;
}
int main(){
	int cases,n,m,cnt,x,i,j,maxx;
	cin>>cases;
	while(cases--){
		memset(cnt0,0,sizeof(cnt0));
		memset(vis,0,sizeof(vis));//初始化 
		cnt=0;
		num0=0;
		cin>>n>>m;
		for(i=0;i<n;i++){
			scanf("%d",&x);
			if(x==0)num0++;//0的数目 
			vis[x]=1;
		}

		cnt=0;
		for(i=1;i<=m;i++){
			if(vis[i]==1){
				cnt0[i]=cnt;
			}
			else{
				cnt++;
				cnt0[i]=cnt;
			}
		}
		int l,r,mid;
		maxx=0;
		for(i=1;i<=m;i++){//枚举起点 
			l=i;r=m;
			while(l+1<=r){//二分 
				mid=r-(r-l)/2;
				if(f(mid,i))l=mid;
				else r=mid-1;
			}
			maxx=max(maxx,l-i+1);//求所有起点情况下的最大值 
		}
		cout<<maxx<<endl;
	}
	return 0;
}
</strong>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值