#优化#洛谷 6032 选择客栈 加强版

题目


分析

考虑(O(nk))的算法在计算颜色的时候有很多冗余状态,
如果多出来一个费用不超过阈值的客栈,可以对前面超过阈值的客栈更新,
由于每个客栈最多被更新一次,所以时间复杂度为(O(n))


代码

#include <cstdio>
#include <cctype>
#include <vector>
#define rr register
using namespace std;
const int N=2000011;
typedef long long lll; lll ans;
int n,k,m,cnt[N],col[N],cost[N];
inline signed iut(){
    rr int ans=0; rr char c=getchar();
	while (!isdigit(c)) c=getchar();
	while (isdigit(c)) ans=(ans<<3)+(ans<<1)+(c^48),c=getchar();
	return ans; 
}
signed main(){
	n=iut(),k=iut(),m=iut();
	for (rr int i=1;i<=n;++i){
		col[i]=iut(),cost[i]=iut();
		if (cost[i]<=m){
			for (rr int j=i-1;cost[j]>m;--j)
			    ++cnt[col[j]];
		}
		ans+=cnt[col[i]];
		if (cost[i]<=m) ++cnt[col[i]];
	}
	return !printf("%lld",ans);
} 
原文地址:https://www.cnblogs.com/Spare-No-Effort/p/13922328.html