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
Sample Output
题意:求最长有序子串,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>