python语言创始人、cpp创始人_8.30 文远知行笔试 AC3 题解PythonCpp

本文提供了三道编程题的解答,包括使用Python的动态规划解决二维数组问题,C++中处理字符变换避免溢出的方法,以及利用BFS解决树的路径计数问题。同时,作者请求算法岗位的内推机会。
摘要由CSDN通过智能技术生成

占个坑,等结束发题解。

另外求算法岗内推,救救孩子。

第一题

动态规划,可以压到1维。

按照代价值来做DP,同时记录收益值,当代价值相同的时候取收益最大的那个。

"""

3 4

1 6 3 20

8 4 2 2

1 1 3 1

1 2 2 2

2 2 2 2

2 3 2 2

"""

def solve(row, col, costs, values):

dp1 = [0] * col

dp2 = [0] * col

for j in range(col):

if j == 0:

dp1[j] = costs[0][j]

dp2[j] = values[0][j]

continue

dp1[j] = dp1[j - 1] + costs[0][j]

dp2[j] = dp2[j - 1] + values[0][j]

for i in range(1, row):

cdp1 = [0] * col

cdp2 = [0] * col

for j in range(col):

if j == 0:

cdp1[j] = costs[i][j] + dp1[j]

cdp2[j] = values[i][j] + dp2[j]

continue

if cdp1[j - 1] < dp1[j]:

cdp1[j] = cdp1[j - 1] + costs[i][j]

cdp2[j] = cdp2[j - 1] + values[i][j]

elif cdp1[j - 1] > dp1[j]:

cdp1[j] = dp1[j] + costs[i][j]

cdp2[j] = dp2[j] + values[i][j]

else:

cdp1[j] = cdp1[j - 1] + costs[i][j]

cdp2[j] = values[i][j] + max(cdp2[j - 1], dp2[j])

dp1 = cdp1[:]

dp2 = cdp2[:]

print("{} {}".format(dp1[-1], dp2[-1]))

if __name__ == '__main__':

row, col = map(int, input().split())

costs = []

values = []

for i in range(row):

costs.append(list(map(int, input().split())))

for i in range(row):

values.append(list(map(int, input().split())))

solve(row, col, costs, values)

第二题

禁用了Python,题目的大意是制定一个字母,然后指定次数和每次变换跳的步数,求最终字母编程多少。 给的次数和每次跳的步数范围很大。利用:

防止溢出就可以。 c++ 字符操作不太会写,用的强制类型转换。

#include

using namespace std;

int main(){

int MOD= 26;

int _;

cin >> _;

for(int i =0; i < _; ++i){

char a;

long long int n, k;

cin >> a >> n >> k;

long long int ret = ((n % MOD) * (k % MOD)) % MOD;

long long int out = ret + a;

if(out > 'z'){

out = out - 'z' + 'a' - 1;

}

cout << char(out) << endl;

}

}

第三题

BFS。N个点 N-1个边,因此是一棵树,直接BFS就可以

from collections import defaultdict, deque

def solve(N, Q, graph, samples):

def bfs(s, e, c):

que = deque()

que.append([s, 0])

visited = set()

visited.add(s)

while que:

node, cnt = que.popleft()

for _node in graph[node]:

if _node not in visited:

visited.add(_node)

distance = graph[node][_node]

times = distance // c

ccnt = cnt

if times == 0:

ccnt = cnt + 1

elif times * c == distance:

ccnt = cnt + times

else:

ccnt = cnt + times + 1

if _node == e:

return ccnt + 1

que.append([_node, ccnt])

for [s, e, c] in samples:

ret = bfs(s, e, c)

print(ret)

if __name__ == '__main__':

N, Q = map(int, input().split())

graph = defaultdict(dict)

for i in range(N - 1):

u, v, d = map(int, input().split())

graph[u][v] = d

graph[v][u] = d

samples = []

for i in range(Q):

samples.append(list(map(int, input().split())))

solve(N, Q, graph, samples)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值