华为9.21笔试


2022/9/21 华为留学生

题目2 两数之和

m = int(input())
x = list(map(int, input().split(' ')))
s = int(input())
y = list(map(int, input().split(' ')))

def func(m, x, s, y):
    cnt = 0
    hashmap = dict()
    for i in range(m):
        for j in range(s):
            if y[j] - x[i] in hashmap:
                cnt += 1
            hashmap[x[i]] = i
    return cnt
print(func(m,x,s,y))

"""
8
1 2 3 5 7 9 10 12
2
4 12
"""

题目3 拓扑排序

#华为9.21 第三题拓扑排序
from collections import deque

n, r = map(int, input().split())
nums = list(map(int, input().split()))
indegre = {}
nxs = {}
for num in nums:
    indegre[num] = 0
    nxs[num] = []
for i in range(r):
    a, b = map(int, input().split())
    indegre[b] += 1
    nxs[a].append(b)
rest = []

class Solution:
    def bfs(self, nums, indegre, nxs, rest):
        queue = deque()
        for num in nums:
            if indegre[num] == 0 and len(nxs[num]) != 0:
                queue.append(num)
            nxs[num].sort()
            if indegre[num] == 0 and len(nxs[num]) == 0:
                rest.append(num)
#拓扑排序
        res = []
        while len(queue):
            curr = queue.popleft()
            res.append(curr)
            for nx in nxs[curr]:
                indegre[nx] -= 1
                if indegre[nx] == 0: queue.append(nx)
#处理rest
        for num in rest:
            if indegre[num] == 0 and len(nxs[num]) == 0:
                if num <= res[0]:
                    res = [num] + res
                elif num >= res[-1]:
                    res = res + [num]
                else:
                    for i in range(1,len(res)-1):
                        if res[i] <= num and num <= res[i+1]:
                            res = res[:i+1] + [num] + res[i+1:]
                            break
#输出
        if len(res) == 0: print(-1)
        else:
            for i in range(len(res)-1):
                print(res[i], end = ' ')
            print(res[-1])

a = Solution()
a.bfs(nums,indegre,nxs,rest)

"""
6 5
0 1 2 3 4 5
0 1
1 2
1 3
2 3
3 4
"""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值