【MC0204】世界警察

世界警察小码哥来谈判了,恐怖分子在银行挟持了 n 个人质,每个人质都所属一个国家,第 i 个人质所属的国家为 ��ci,人质排成了一排,位置都是固定的。经过商讨,恐怖分子允许小码哥可以带走任意一段连续区间内的人质。但是上级要求小码哥,最好每个国家的人质都带回来一个,不希望人质中有重复的国家。请问小码哥最多可以带出来多少人质。

格式
输入格式:

第一行一个正整数 n,表示共有 n 个人质;
第二行共有 n 个正整数,第 i 个正整数表示第 i 个人质的所属国家 ��ci

输出格式:

一个整数表示小码哥最多可以带出来的人质数。

样例 1
输入:
5
1 1 2 3 4
复制
输出:
4
复制
备注

其中:1≤�≤1061n106;0≤��≤1090ci109。

本题相关知识点: 杂项:双指针
 
 
题解:暴力代码合理超时:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<bits/stdc++.h>
using namespace std;
int n,ans=-1,a[1000004],b[1000004];

bool pd(int x,int y){
    int cnt=0;
    for(int i=x;i<=y;i++)
        b[++cnt]=a[i];
    sort(b+1,b+cnt+1);
    for(int i=1;i<cnt;i++)
        if(b[i]==b[i+1]) return 0;
    return 1;
}

int main(){
    freopen("5.in","r",stdin);
    freopen("5.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    for(int i=1;i<=n;i++){
        for(int j=i;j<=n;j++){
            if(pd(i,j)==1) 
               ans=max(ans,j-i+1);
        }
    }
    //cout<<pd(1,5)<<endl;
    cout<<ans;
    return 0;
}
// 1 1 2 3 4 1 4 

正解:map一一对应 实现桶的作用

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<bits/stdc++.h>
using namespace std;
int n,a[1000004],ans,num;
map<int,int>mp; 
int main(){
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    int l=1,r=1;
    while(l<=r && r<=n){
        if(mp[a[r]]==0){
            mp[a[r]]++; r++; num++;
            ans=max(ans,num);
        }
        else{
            while(a[l]!=a[r]) 
                { mp[a[l]]--; l++; num--; }
            mp[a[l]]--; l++; num--;
        }
    }
    cout<<ans;
    return 0;
}

 

posted @ 2024-04-10 16:42  #Cookies#  阅读(24)  评论(0编辑  收藏  举报