地址 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 ", 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 ", 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 ",minLen); 64 65 66 return 0; 67 }