2018-05-26 Network Attack

今天在pycheck.io上做到了另一个有意思的题

题为 Network Attack

Nicola regularly inspects the local networks for security issues. He uses a smart and aggressive program which takes control of computers on the network. This program attacks all connected computers simultaneously, then uses the captured computers for further attacks. Nicola started the virus program in the first computer and took note of the time it took to completely capture the network. We can help him improve his process by modeling and improving his inspections.

We are given information about the connections in the network and the security level for each computer. Security level is the time (in minutes) that is required for the virus to capture a machine. Capture time is not related to the number of infected computers attacking the machine. Infection start from the 0th computer (which is already infected). Connections in the network are undirected. Security levels are not equal to zero (except infected).

Information about a network is represented as a matrix NxN size, where N is a number of computers. If ith computer connected with jth computer, then matrix[i][j] == matrix[j][i] == 1, else 0. Security levels are placed in the main matrix diagonal, so matrix[i][i] is the security level for the ith computer.

题目大意是:

存在一个n*n矩阵M,M[i][j]=M[j][i]= 0 or 1 表示从电脑i到电脑j的可连通性,M[i][i]表示第i台电脑的防御强度(从刚开始被连接到被成功感染需要的时间)。

你的母机是防御强度为0的机器(此题中定为0号),现要返回感染所有机器需要的时间。


扫描二维码关注公众号,回复: 1528342 查看本文章

拙劣的分析:

1、返回的res可以在循环里累加

2、矩阵只需要操作上半部分

3、设置一个列表作为感染机的存储列表,当长度达到n时结束循环

4、矩阵的防御强度可以作为一个倒计时器,每次循环执行一次(是/相邻)感染机的判断


由此可以写出代码如下:

def capture(M):
    n = len(M)
    virus = [0] # 储存肉鸡
    tick = 0 # 时间计数
    while len(virus) < n:
        tick += 1
        affected = [] # 避免感染重复发生
        for i in virus:
            for j in range(n):
                if i == j or j in virus:
                    continue
                elif M[i][j] == 1 and j not in affected:
                    M[j][j] -= 1 # 倒计时器
                    affected.append(j)
        for k in range(n): # 若在感染完立即判断添加肉鸡,会导致i在遍历时取值为刚添加的肉鸡,不符合逻辑
            if M[k][k]==0 and k not in virus:
                virus.append(k)
    return tick

猜你喜欢

转载自blog.csdn.net/contr4l_/article/details/80461380