POJ3061
解析详见挑战程序设计竞赛。
#include <set>
#include <map>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#define PI acos(-1.0)
#define MOD 1000000009
#define INF 0x3f3f3f3f
#define Lowbit(x) (x & (-x))
#define mem(a,x) memset(a,x,sizeof(a))
#define Read() freopen("in.txt", "r", stdin);
#define Write() freopen("out.txt", "w", stdout);
#define bitnum(a) __builtin_popcount(a)
using namespace std;
typedef long long int ll;
inline int in()
{
ll res=0;char c;ll f=1;
while((c=getchar())<'0' || c>'9')if(c=='-')f=-1;
while(c>='0' && c<='9')res=res*10+c-'0',c=getchar();
return res*f;
}
int n,S;
int a[111111];
int sum[111111];
void solve(){
for(int i=0;i<n;i++){
sum[i+1] = sum[i] + a[i];
}
if(sum[n] < S){
printf("0\n");
return;
}
int res = n;
for(int s = 0;sum[s] + S <= sum[n];s++){
int t = lower_bound(sum+s,sum+n,sum[s]+S)-sum;
res = min(res,t-s);
//cout<<res<<endl;
}
printf("%d\n",res);
}
void solve2(){
int res = n+1;
int s = 0,t = 0 ,sum = 0;
while(1){
while(t < n && sum < S){
sum += a[t++];
}
if(sum < S) break;
res = min(res,t - s);
sum -= a[s++];
}
if(res > n){
res = 0;
}
printf("%d\n",res);
}
// 5 1 3 5 10 7 4 9 2 8
int main(){
int t;scanf("%d",&t);
while(t--){
n = in(); S = in();
for(int i=0;i<n;i++) a[i] = in();
solve2();
}
return 0;
}
POJ3320
mp.size()也能和set一样用。map记录出现的次数,添加的时候为0,说明是新添加的元素,删除的时候为0说明彻底删除了某个元素。
int a[1111111];
int main(){
while(scanf("%d",&n)!=EOF){
map<int,int>mp;
for(int i=0;i<n;i++){
a[i] = in();
mp[a[i]] ++;
}
int num = mp.size(); mp.clear();
int j=0,ans=INF,cnt = 0; // i是开头,j是结尾
for(int i=0;i<n;i++){
for(;j<n&& cnt < num;j++){
if(mp[a[j]]++ == 0){
cnt++;
}
}
if(cnt < num) break;
ans = min(ans,j-i);
if((--mp[a[i]]) == 0) cnt--;
}
printf("%d\n",ans);
}
return 0;
}