第五题不知哪里出问题,总是50%,不是时间复杂度和空间复杂度问题,总是出现语法错误和数组越界,是输入问题吗?求解 def dfs(item, temp_dict, result):
if item in result:
return
result.add(item)
for x in temp_dict[item]:
dfs(x, temp_dict, result)
if __name__ == "__main__":
import sys
N = int(sys.stdin.readline().strip())
M = int(sys.stdin.readline().strip())
if M > 0:
line = sys.stdin.readline().strip()
relation = list(map(int, line.split()))
bucket = {}
for i in range(0, 2 * M, 2):
if relation[i + 1] not in bucket:
bucket[relation[i + 1]] = []
bucket[relation[i + 1]].append(relation[i])
cnt = 0
for key in bucket.keys():
a = set()
dfs(key, bucket, a)
a.add(key)
if len(a) == N:
cnt += 1
print(cnt)
else:
print(N)
第五题网红,暴力解了,为什么一直50%,而且不是超时和数组越界的问题,不解 import sys
import queue
'''
input:3
3
1 2 2 1 2 3
output:1
'''
if __name__ == '__main__':
N = int(sys.stdin.readline().strip())
M = int(sys.stdin.readline().strip())
line = sys.stdin.readline().strip().split()
relationshape = []
Nmatrix = [[0 for i in range(N)] for j in range(N)]
for i in range(M):
tmp = (int(line[2*i]),int(line[2*i+1]))
relationshape.append(tmp)
for i in relationshape:
tmpi = i[0]-1
tmpj = i[1]-1
Nmatrix[tmpi][tmpj] = 1
for i in range(N):
if(Nmatrix[i][tmpi]==1):
Nmatrix[i][tmpj]=1
# print(Nmatrix)
result = 0
for i in range(N):
count = 0
for j in range(N):
if(Nmatrix[j][i]==1 and j!=i):
count+=1
if(count == N-1):
result += 1
print(result)