地址 http://poj.org/problem?id=3320
解答
使用双指针 在指针范围内是否达到要求
若不足要求则从右进行拓展 若满足要求则从左缩减区域
代码如下 正确性调整了几次 然后被输入卡TLE卡了很久都没意识到.........
#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <assert.h>
#include <stdio.h> using namespace std; int n, m; const int MAX_N = ; int v[MAX_N]; set<int> setint; int minLen = ; int main()
{
cin >> n; for (int i = ; i < n; i++) {
//cin >> v[i];
scanf("%d",&v[i]);
setint.insert(v[i]);
} int total = setint.size(); int l = ; int r = ;
map<int, int> mapcover;
mapcover[v[l]]++;
int count = ; while() {
while (count < total) {
r++;
if (r >= n) {
printf("%d\n", minLen);
return ;
}
mapcover[v[r]]++;
if (mapcover[v[r]] == ) {
//说明添加了一个新类型
count++;
}
} if (count < total) {
break;
} minLen = min(minLen, r - l + ); //尝试缩小整个范围 从左端减少
mapcover[v[l]]--;
if (mapcover[v[l]] == ) {
//说明减少了一个种类
count--;
}
l++;
} printf("%d\n", minLen);
return ;
}
ac code 1
#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <assert.h>
#include <stdio.h> using namespace std; int n, m; const int MAX_N = ; int v[MAX_N]; set<int> setint; int minLen = ; int main()
{
cin >> n; for (int i = ; i < n; i++) {
scanf("%d",&v[i]);
setint.insert(v[i]);
} int total = setint.size(); int l = ; int r = ;
map<int, int> mapcover;
mapcover[v[l]]++;
int count = ;
while () {
if (count < total) {
r++;
if (r >= n) break;
mapcover[v[r]]++;
//添加了一个新元素 那么元素种类计数+1
if (mapcover[v[r]] == ) count++; }
else if(count == total) {
minLen = min(minLen, r - l + );
mapcover[v[l]]--;
if (mapcover[v[l]] == ) {
count--;
}
l++;
if (l >= n) break;
if (l > r) {
r = l;
}
}
else {
assert();
} } printf("%d\n",minLen); return ;
}
ac code 2