STL or Force --- CSU 1553: Good subsequence
Good subsequence#
Problem's Link: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1553
#
Mean:
给你一个长度为n的序列和一个值k,让你找出一个子序列,满足在这个子序列中max-min的值<=k,求这个子序列最长的长度。
analyse:
这题做法很多,直接暴力枚举每一个数为起点。
Time complexity: O(n)
Source code:
方法一(暴力):

// Memory Time // 1347K 0MS // by : crazyacking // 2015-03-30-16.02 #include<map> #include<queue> #include<stack> #include<cmath> #include<cstdio> #include<vector> #include<string> #include<cstdlib> #include<cstring> #include<climits> #include<iostream> #include<algorithm> #define MAXN 1000010 #define LL long long using namespace std; int n,k; vector<int> ve; int main() { ios_base::sync_with_stdio(false); cin.tie(0); // freopen("C:\\Users\\Devin\\Desktop\\cin.cpp","r",stdin); // freopen("C:\\Users\\Devin\\Desktop\\cout.cpp","w",stdout); while(cin>>n>>k) { ve.clear(); for(int i=0;i<n;++i) { int tmp; cin>>tmp; ve.push_back(tmp); } int ans=1; for(int i=0;i<n;++i) { int cnt=1; int maxx=ve[i]; int minn=ve[i]; for(int j=i+1;j<n;++j) { if(ve[j]>=maxx) { maxx=ve[j]; } if(ve[j]<=minn) { minn=ve[j]; } if(maxx-minn>k) break; cnt++; } if(cnt>ans) ans=cnt; } cout<<ans<<endl; } return 0; } /* */
方法二(STL):
做法很巧妙,用一个multiset来维护:加入当前这个数后满足条件的连续子序列,也就是说每一轮循环set中的元素都是满足条件的。

// Memory Time // 1347K 0MS // by : crazyacking // 2015-03-30-15.53 #include<map> #include<queue> #include<stack> #include<cmath> #include<cstdio> #include<vector> #include<set> #include<string> #include<cstdlib> #include<cstring> #include<climits> #include<iostream> #include<algorithm> #define MAXN 1000010 #define LL long long using namespace std; int n,k; multiset<int> se; vector<int> ve; int main() { ios_base::sync_with_stdio(false); cin.tie(0); // freopen("C:\\Users\\Devin\\Desktop\\cin.cpp","r",stdin); // freopen("C:\\Users\\Devin\\Desktop\\cout.cpp","w",stdout); while(cin>>n>>k) { se.clear(); ve.clear(); for(int i=0;i<n;++i) { int tmp; cin>>tmp; ve.push_back(tmp); } int ans=1; for(int i=0,j=0;i<n;++i) { se.insert(ve[i]); for(;*se.rbegin()-*se.begin()>k;j++) { se.erase(ve[j]); } if(i-j+1>ans) ans=i-j+1; } cout<<ans<<endl; } return 0; } /* */
作者:北岛知寒
出处:https://www.cnblogs.com/crazyacking/p/4378466.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?