Acwing3378.代理服务器【贪心】

1.题目
题目描述:点击这里
Attention!!! 这道题是清华大学2009年研究生复试机试题

2.解题思路
贪心思想:我们每次选能够坚持最久不换的代理服务器,也就是遍历输入的m个ip地址,同时记录当前出现过的代理服务器ip;一旦当遍历到某个ip地址时,发现所有的代理服务器ip都出现过,那么记一次转换(即最后发现的这个代理服务器能够坚持最久)同时更新记录(注意:一定要将上一次发生转换的代理服务器ip加入下一轮记录)这里使用set作为存储的数据结构。

3.代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <vector>
#include <set>

using namespace std;
const int MAXN=1010,MAXM=5010;

int n,m;
set<string> proxy;
set<string> base;

int main(void)
{
    
    
    cin>>n;
    
    for(int i=1;i<=n;i++){
    
    
        string p;
        cin>>p;
        base.insert(p);
    }

    cin>>m;
    int ans=0;
    bool flag=false;
    
    for(int i=1;i<=m;i++){
    
    
        string ip;
        cin>>ip;
        
        if(base.count(ip)&&!proxy.count(ip)){
    
    
            proxy.insert(ip);
            flag=true;
            
            if(base.size()==proxy.size()){
    
    
                ans++;
                proxy.clear();
                proxy.insert(ip);
            }
        }
    }
    
    if(n==1&&flag) ans=-1;//特殊情况,只有1个代理服务器并且还没有可以更换的代理服务器,flag为true表示序列中出现了需要更换的情况
    cout<<ans<<endl;
    
    return 0;
}

有点感想:算法题的魅力就在于,当你自我感觉不菜时,总有一道不那么难的题坑死你,当你自我感觉滑向深渊时,总有一道不简单的题给你信心。
:- )

おすすめ

転載: blog.csdn.net/qq_43579980/article/details/119961115