当代理服务器和要访问的目的服务器的IP地址相同时需要切换代理服务器,本题要求代理服务器切换的次数最少。
由于要访问的服务器的IP地址顺序是固定的,因此我们可以遍历代理IP池中的全部IP,看看哪个代理IP可以在切换前代理IP前访问最多的目标IP地址。
- for (int i = 0; i < proxy_list.size(); i++) {
- int j = index;
- //index为当前访问的IP的坐标,以当前访问的IP为起点,看看哪个代理IP可以走的最远
- while (j < m && visit_ip[j]!=proxy_list[i]) {j++;} //只要没碰上相同的IP,也没到终点,就一直走
- max_n = max(max_n,j-index); //max_n是本次切换向右走的最大的步长
- }
需要注意的是,按照题目要求,当不需要切换的时候,需要返回-1
if (max_n == 0) return -1;
- #include <iostream>
- #include<vector>
- #include "math.h"
- using namespace std;
-
-
- int get_cnt(vector<string> proxy_list, vector<string> visit_ip,int m) {
- int index = 0;
- int count = 0;
- while (index < m) {
- int max_n = 0; //向右最长的距离
-
- for (int i = 0; i < proxy_list.size(); i++) {
- int j = index;
- while (j < m && visit_ip[j]!=proxy_list[i]) j++;
- max_n = max(max_n,j-index);
- }
- if (max_n == 0) return -1;
- count++;
- index += max_n;
- }
- return count-1;
- }
-
- int main() {
- int n, m;
- while (cin >> n) {
- vector<string> replace_serve(n);
- for (int i = 0; i < n; i++) {
- cin >> replace_serve[i];
- }
-
- cin >> m;
- vector<string> visit_serve(m);
- for (int i = 0; i < m; i++) {
- cin >> visit_serve[i];
- }
-
- int count = get_cnt(replace_serve, visit_serve,m);
- cout << count << endl;
-
- }
- }