这道题需要采用贪心的策略,即每次选择代理服务器的时候,都要选择从当前位置出发一次能够访问尽可能多的地址,同时要考虑到可能会出现无法访问完的情况,即代理服务器只有一个,而其IP地址正好在要访问的地址中,完整代码如下:
#include<iostream>
#include<string>
using namespace std;
const int N = 1000 + 10;
const int M = 5000 + 10;
string proxy[N], go[M];
int main(){
int n, m;
while(cin>>n){
for(int i = 0;i < n;i++) cin>>proxy[i];
cin>>m;
for(int i = 0;i < m;i++) cin>>go[i];
bool flag = true;
int count = -1; //第一次切换不算
int index = 0; //用于标识访问的IP地址
while(flag && index < m){
int max = 0;
for(int i = 0;i < n;i++){ //找到可以访问地址数最多的代理服务器
int j = index;
while(j < m&&proxy[i] != go[j]) j++;
if(j - index > max) max = j - index;
}
if(max == 0) flag = false; //说明无法移动,即找不到安排方式
count++;
index += max;
}
if(flag) cout<<count<<endl;
else cout<<-1<<endl;
}
return 0;
}