<挑战程序设计竞赛> poj 3320 Jessica's Reading Problem 双指针
地址 http://poj.org/problem?id=3320
解答
使用双指针 在指针范围内是否达到要求
若不足要求则从右进行拓展 若满足要求则从左缩减区域
代码如下 正确性调整了几次 然后被输入卡TLE卡了很久都没意识到.........

1 #include <iostream> 2 #include <map> 3 #include <set> 4 #include <algorithm> 5 #include <assert.h> 6 #include <stdio.h> 7 8 9 using namespace std; 10 11 int n, m; 12 13 const int MAX_N = 1000010; 14 15 int v[MAX_N]; 16 17 set<int> setint; 18 19 int minLen = 999999; 20 21 22 int main() 23 { 24 cin >> n; 25 26 for (int i = 0; i < n; i++) { 27 //cin >> v[i]; 28 scanf("%d",&v[i]); 29 setint.insert(v[i]); 30 } 31 32 int total = setint.size(); 33 34 int l = 0; int r = 0; 35 map<int, int> mapcover; 36 mapcover[v[l]]++; 37 int count = 1; 38 39 while(1) { 40 while (count < total) { 41 r++; 42 if (r >= n) { 43 printf("%d\n", minLen); 44 return 0; 45 } 46 mapcover[v[r]]++; 47 if (mapcover[v[r]] == 1) { 48 //说明添加了一个新类型 49 count++; 50 } 51 } 52 53 if (count < total) { 54 break; 55 } 56 57 minLen = min(minLen, r - l + 1); 58 59 //尝试缩小整个范围 从左端减少 60 mapcover[v[l]]--; 61 if (mapcover[v[l]] == 0) { 62 //说明减少了一个种类 63 count--; 64 } 65 l++; 66 } 67 68 69 printf("%d\n", minLen); 70 return 0; 71 }

1 #include <iostream> 2 #include <map> 3 #include <set> 4 #include <algorithm> 5 #include <assert.h> 6 #include <stdio.h> 7 8 9 using namespace std; 10 11 int n, m; 12 13 const int MAX_N = 1000010; 14 15 int v[MAX_N]; 16 17 set<int> setint; 18 19 int minLen = 999999; 20 21 int main() 22 { 23 cin >> n; 24 25 for (int i = 0; i < n; i++) { 26 scanf("%d",&v[i]); 27 setint.insert(v[i]); 28 } 29 30 int total = setint.size(); 31 32 int l = 0; int r = 0; 33 map<int, int> mapcover; 34 mapcover[v[l]]++; 35 int count = 1; 36 while (1) { 37 if (count < total) { 38 r++; 39 if (r >= n) break; 40 mapcover[v[r]]++; 41 //添加了一个新元素 那么元素种类计数+1 42 if (mapcover[v[r]] == 1) count++; 43 44 } 45 else if(count == total) { 46 minLen = min(minLen, r - l + 1); 47 mapcover[v[l]]--; 48 if (mapcover[v[l]] == 0) { 49 count--; 50 } 51 l++; 52 if (l >= n) break; 53 if (l > r) { 54 r = l; 55 } 56 } 57 else { 58 assert(0); 59 } 60 61 } 62 63 printf("%d\n",minLen); 64 65 66 return 0; 67 }
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
2014-12-19 C++ 提取网页内容系列之四正则