您的位置:首页 > 其它

清华考研复试上机——代理服务器

2018-01-15 19:18 537 查看
使用代理服务器能够在一定程度上隐藏客户端信息,从而保护用户在互联网上的隐私。我们知道n个代理服务器的IP地址,现在要用它们去访问m个服务器。这m 个服务器的 IP 地址和访问顺序也已经给出。系统在同一时刻只能使用一个代理服务器,并要求不能用代理服务器去访问和它 IP地址相同的服务器(不然客户端信息很有可能就会被泄露)。在这样的条件下,找到一种使用代理服务器的方案,使得代理服务器切换的次数尽可能得少。
[b]输入描述:[/b]
    每个测试数据包括 n + m + 2 行。
    第 1 行只包含一个整数 n,表示代理服务器的个数。
    第 2行至第n + 1行每行是一个字符串,表示代理服务器的 IP地址。这n个 IP地址两两不相同。
    第 n + 2 行只包含一个整数 m,表示要访问的服务器的个数。
    第 n + 3 行至第 n + m + 2 行每行是一个字符串,表示要访问的服务器的 IP 地址,按照访问的顺序给出。
    每个字符串都是合法的IP地址,形式为“xxx.yyy.zzz.www”,其中任何一部分均是0–255之间的整数。输入数据的任何一行都不包含空格字符。
     其中,1<=n<=1000,1<=m<=5000。


[b]输出描述:[/b]
    可能有多组测试数据,对于每组输入数据, 输出数据只有一行,包含一个整数s,表示按照要求访问服务器的过程中切换代理服务器的最少次数。第一次使用的代理服务器不计入切换次数中。若没有符合要求的安排方式,则输出-1。


示例1

输入

3
166.111.4.100
162.105.131.113
202.112.128.69
6
72.14.235.104
166.111.4.100
207.46.19.190
202.112.128.69
162.105.131.113
118.214.226.52


输出

1


    思路:因为合法的IP地址一定是一个32位整型变量,因此将IP地址转换为整型变量方便比较。然后每次用OPT调度方法选择下一个使用的代理服务器,即每次选择在未来最远的时间不会访问到的代理服务器。每次重新选择就将counter增加1,直到选择了一个永远不会访问到的代理服务器,之后就再也不需要重新调度了。

   代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <memory.h>

int client[1000];
int server[5000];

int convertIPtoInteger(char *str)
{
int len = strlen(str);

int a = 0, b = 0, c = 0, d = 0;
int i = 0;
while(str[i] != '.')
{
a = a * 10 + str[i] - '0';
i++;
}
i++;
while(str[i] != '.')
{
b = b * 10 + str[i] - '0';
i++;
}
i++;
while(str[i] != '.')
{
c = c * 10 + str[i] - '0';
i++;
}
i++;
while(str[i] != '\0')
{
d = d * 10 + str[i] - '0';
i++;
}
return a * 256*256*256 +
b * 256*256 +
c * 256 +
d;
}

// get the optimistic client index, returning true means that it is not necessary to switch client again
bool getLongestIndex(int m, int n, int &nextServer)
{
int flag = nextServer;
for(int i = 0; i < n; i++)
{
int next = flag;
while(server[next] != client[i] && next < m) next++;
if(next > nextServer)
nextServer = next;
if(next == m) break;
}
if(nextServer == m || nextServer == flag) return true;
else return false;
}

int main()
{
int n, m;
while(scanf("%d", &n) != EOF)
{
char tmp[16];
for(int i=0; i<n; i++)
{
scanf("%s", tmp);
client[i] = convertIPtoInteger(tmp);
}
scanf("%d", &m);
for(int i=0; i<m; i++)
{
scanf("%s", tmp);
server[i] = convertIPtoInteger(tmp);
}

int nextServer = 0;
int counter = 0;
while(!getLongestIndex(m, n, nextServer)) counter++;
if(nextServer != m) printf("-1\n");
else printf("%d\n", counter);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: