AtCoder Beginner Contest 260 E - At Least One

1.暴力解法

        分别枚举长度为1——m(m级别),再枚举好序列的开始位置(m级别)。由于序列的长度和开始位置确定,因此序列确定。再判断是否满足n对数对(n级别)。因此暴力做法至少O(m*m*n)。

2.track 

        当序列l——r满足n对数对时,序列向左,向右扩张时也一定满足。

        根据track,假如满足n对数对的最短长度序列为x,那么长度为x——m-x+1的好序列数量都会加1(差分)。

3.如何确定一个序列是否满足n对数对?

        使用变量cnt记录满足数对的数量,为了以防数对多次反复计算,用map存储出现的次数,只有第一次出现时才是有效的(cnt++)。因此需要用vector存储每个数他可以满足哪些数对。

4.确定最短序列

        枚举最短序列的最右端。如果暴力循环找左端点,时间复杂度为O(m*m),会超时。此时需要deque优化。(x1<x2)当x1与x2两个数都可以满足相同的数对,由于我们需要的是最短序列。那么我们必然选择距离右端点更近的x2。类似于单调队列。

#include<iostream>
#include<vector>
#include<deque>
#include<map>

using namespace std;

const int maxn=2e5+10;

int ans[maxn],n,m,cnt;
vector<int> A[maxn];
map<int,int> M;
deque<int> Q;

bool check(int q)
{
	for(auto x:A[q])
		if(M[x]==1)   return false;
	return true;
}

int main()
{
	scanf("%d%d",&n,&m);
	
	for(int i=1;i<=n;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		A[x].push_back(i),A[y].push_back(i);
	}
	
	for(int r=1;r<=m;r++)
	{
		for(auto x:A[r])
		{
			M[x]++;
			if(M[x]==1)   cnt++;
		}
		while(Q.size()&&check(Q.front()))      //check()函数判断这个值是否可以被替换 
		{
			for(auto x:A[Q.front()])
				M[x]--;
			Q.pop_front();
		}
		
		if(cnt==n)
		{
			if(Q.size())
				ans[r-Q.front()+1]++;
			else                     //小细节,当Q为空时,最小长度为1 
				ans[1]++;
			ans[r+1]--;
		}
//		cout<<r<<endl;
		Q.push_back(r);
	}
	
	for(int i=1;i<=m;i++)
	{
		ans[i]+=ans[i-1];
		printf("%d ",ans[i]);
	}
	
	return 0;
}

 

 

 

#include<iostream>
#include<vector>
#include<algorithm>
#ifndef debug
#define debug(args...)
#define debugArr(begin,end)
#endif
#define mulcase int tt;cin>>tt;while(tt--)
using namespace std;
using ll=long long;
const int N=2e5+10;
int n,m,f[N];
vector<int> v[N];
int cnt[N],tot;
int vis[N];
int c[N];

int main() {
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>n>>m;
	
	for (int i=1,a,b; i<=n; ++i){
		cin>>a>>b;

		v[a].push_back(i);
		v[b].push_back(i);
	}
	
	int l=0;
	for (int r=1; r<=m; ++r){
		for(int x:v[r]){
			if(++cnt[x]==1)
				tot++;
			if(vis[x]&&cnt[x]==2)
				c[l]++;
		}
		if(tot!=n) continue;
		
		while(c[l]==v[l].size()){
			for(int x:v[l]){
				vis[x]=0;
				cnt[x]--;
			}  
			l++;
			for(int x:v[l]){
				vis[x]=1;
				if(cnt[x]==2) c[l]++;
			} 
		}
		f[r-l+1]++,f[r+1]--;
	}
	
	for (int i=1; i<=m; ++i) 
	{
		f[i]+=f[i-1];
		cout<<f[i]<<" ";
	}
	return 0;
}
/*











*/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

~顾安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值