The Longest Straight FZU - 2216(模拟或二分)

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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值