E - The Longest Straight
题目链接: FZU - 2216题意:n张纸牌, 数字0可以变成任意数字, 纸牌上最大数不能大于m;求n张纸牌中连续的最长的纸牌序列长度(可以使用数字为0的纸牌);
思路:比赛的时候直接模拟 ,用有数字0的纸牌将不连续的连起来, 最长能连几张;然后一直滚动;
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <queue>
using namespace std;
const int maxn=1e5+10;
int vis[maxn], cnt[maxn];
int main(){
int T;
scanf("%d", &T);
while(T--){
int x, n, m;
scanf("%d%d", &n, &m);
int zero=0;
memset(cnt, 0, sizeof(cnt));
memset(vis, 0, sizeof(vis));
for(int i=0; i<n; i++){
scanf("%d", &x);
if(x==0) zero++;
vis[x]=1;
}
queue<int> q;
int ans=0, num=0, l, r;
l=0, r=0;
for(int i=1; i<=m; i++){
if(!vis[i]&&num<zero){//如果有零未用, 用零代替i;左区间不变, 右区间右移;将该零的位置放入queue;
q.push(i);
r++;
num++;
}
else if(!vis[i]){//如果零用完了, 讲第一个零拿过来代替i;左区间移动到之前第一个零的位置;
q.push(i);
l=q.front();
q.pop();
r++;
}
else{
r++;
}
ans=max(r-l, ans);
}
printf("%d\n", ans);
}
return 0;
}
比赛结束后搜的博客, 发现竟然全是二分做的;
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <stdio.h>
using namespace std;
const int maxn=1e5+10;
int vis[maxn], cnt[maxn];
int main(){
int T;
scanf("%d", &T);
while(T--){
int x, n, m;
scanf("%d%d", &n, &m);
int zero=0;
memset(cnt, 0, sizeof(cnt));
memset(vis, 0, sizeof(vis));
for(int i=0; i<n; i++){
scanf("%d", &x);
if(x==0) zero++;
vis[x]=1;
}
for(int i=1; i<=m; i++){
if(!vis[i]) cnt[i]=cnt[i-1]+1;
else cnt[i]=cnt[i-1];
}
int ans=0;
for(int i=0; i<=m; i++){
int left=i, right=m;
while(left<=right){
int mid=right-(right-left)/2;
if(cnt[mid]-cnt[i]>zero) right=mid-1;
else left=mid+1;
}
ans=max(ans, right-i);
}
printf("%d\n", ans);
}
return 0;
}