贪心,选择可以每一次使用最久的代理服务器,需要注意区别第一次切换之前和切换之后的区别。第一次切换之后需要选择一个代理服务器作为当前服务器,因此判断条件需要改变。

#include<iostream>
#include<map>

using namespace std;

int main(){
    int n,m;
    while(cin>>n){
        map<string,bool>proxyServer;//定义一个map储存代理服务器和其状态(是否使用)
        for(int i=0;i<n;i++){//读入代理服务器
            string str;
            cin>>str;
            proxyServer.insert(make_pair(str, true));
        }
        int res=0,count=0;//res为切换次数,count用于记录使用过的代理服务器数量,判断是否切换代理服务器
        cin>>m;
        for(int i=0;i<m;i++){//循环读入需要访问的服务器
            string str;
            cin>>str;
            if(proxyServer.count(str)==1&&proxyServer[str]==true){//当前需要访问的服务器为代理服务器,并且此代理服务器在当前循环中未被使用过
                proxyServer[str]=false;
                count++;//使用过的代理服务器数量
            }
            if(count==n){//当所有代理服务器都被使用过
                res++;//切换当前使用的服务器
                for(auto &this:proxyServer){//遍历重置代理服务器状态
                    this.second=true;
                }
                proxyServer[str]=false;//此处与第一轮查找不同,需要标记当前使用的服务器
                count=1;//当前有正在使用的服务器,所以使用过的服务器数量为1
            }
        }
        if(n==1&&res!=0){//代理服务器数量为1,但是需要切换代理服务器,所以不符合条件
            cout<<-1<<endl;
        }
        else{
            cout<<res<<endl;
        }
    }
    return 0;
}