携程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

相关推荐

03-23 15:00
已编辑
厦门大学 Java
xiaowl:你这个简历的问题是对于技术点、项目的描述,都是描述action的,对于面试官而言,仅能知道你干了什么,无法判断你为什么这么干,干的好不好。
点赞 评论 收藏
分享
03-27 01:58
已编辑
西北工业大学 Java
在平静中度过当下:如果这个bg也简历挂的话可能他们现在不缺人了吧,我也是这两天投的,阿里和快手投的岗都是简历秒挂
点赞 评论 收藏
分享
评论
1
5
分享

创作者周榜

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