携程3.18日算法笔试

1. 给n个点(0到n-1)和n-1条有方向的路径,要求最终在0位置集合,需要修改多少条路径的方向
n,l = input().split()
n=int(n)
l = l.replace('[','')
l = l.replace(']','')
nums = [int(i) for i in l.split(',')]
linjiebiao = [[] for i in range(n)]
paths = [[] for i in range(n)]
for i in range(n-1):
    a, b = nums[2*i], nums[2*i+1]
    linjiebiao[a].append(b)
    linjiebiao[b].append(a)1 2 3 4<trip>5 10 5 7
    paths[a].append(b)
ans = 0
def dfs(i):
    global ans
    visited.append(i)
    for to in linjiebiao[i]:
        if to not in visited:
            if i not in paths[to]:
                ans+=1
            dfs(to)

visited = []
dfs(0)
print(ans)
2. 计算自注意力机制的结果
import numpy as np

def softmax(x):
    x_row_max = x.max(axis=-1)
    x_row_max = x_row_max.reshape(list(x.shape)[:-1]+[1])
    x = x - x_row_max
    x_exp = np.exp(x)
    x_exp_row_sum = x_exp.sum(axis=-1).reshape(list(x.shape)[:-1]+[1])
    softmax = x_exp / x_exp_row_sum
    return softmax

nums = [list(map(int,line.split())) for line in input().split('<trip>')]
d = int(input())
inputs = np.array((nums))
Q, K, V = np.ones((inputs.shape[1],d))*0.5,np.ones((inputs.shape[1],d))*0.5,np.ones((inputs.shape[1],d))*0.5
query, key, value = np.matmul(inputs, Q), np.matmul(inputs, K), np.matmul(inputs, V)
tmp = np.matmul(key, query.transpose())

tmp = softmax(tmp)
out = np.matmul(tmp, value)
out = out*np.sqrt(inputs.shape[1])#len(inputs)
for i in range(len(nums)-1):
    for j in range(d):
        if j==d-1:
            print("%.2f" % out[i][j], end='<trip>')
        else: print("%.2f" % out[i][j], end=' ')
for j in range(d):
    if j==d-1:
        print("%.2f" % out[len(nums)-1][j])
    else: print("%.2f" % out[len(nums)-1][j], end=' ')


#携程##笔试题目#
全部评论
我的第一题是计算缘分值,给两个人的拼音字符串,剔除相同部分,每个字符串剩余部分转换为ASCII中的数值计算。第二题考察AC自动机算法,真是无语
点赞 回复 分享
发布于 2021-03-18 20:57
第二题咋做啊, 我手算出来都是13.5  13.5 13.5
点赞 回复 分享
发布于 2021-03-18 20:54
老哥牛逼
点赞 回复 分享
发布于 2021-03-18 20:53

相关推荐

评论
1
5
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务