解题思路:
递归。
注意事项:
参考代码:
def dfs(x,cnt,now): global n,m,A,vis,ans if cnt == m: if now > ans: ans = now return if n-x < 2*(m-cnt)-1: #重要优化 return if x == 0: if (not vis[x]) and (not vis[x+1]) and (not vis[n-1]): vis[x] = 1 for i in range(x+1,n+1): dfs(i,cnt+1,now+A[x]) vis[x] = 0 else: for i in range(x+1,n+1): dfs(i,cnt,now) elif x == n-1: if (not vis[x]) and (not vis[x-1]) and (not vis[0]): vis[x] = 1 for i in range(x+1,n+1): dfs(i,cnt+1,now+A[x]) vis[x] = 0 else: for i in range(x+1,n+1): dfs(i,cnt,now) else: if (not vis[x]) and (not vis[x-1]) and (not vis[x+1]): vis[x] = 1 for i in range(x+1,n+1): dfs(i,cnt+1,now+A[x]) vis[x] = 0 else: for i in range(x+1,n+1): dfs(i,cnt,now) if __name__ == '__main__': n,m = map(int,input().strip().split()) A = [int(i) for i in input().strip().split()] vis = [0 for i in range(n)] ans = 0 if n < 2*m-1: print('Error!') else: for i in range(n-(2*m-2)): dfs(i,0,0) print(ans)
0.0分
1 人评分
C二级辅导-计负均正 (C语言代码)浏览:652 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:672 |
C语言程序设计教程(第三版)课后习题6.2 (C语言代码)浏览:1432 |
WU-整数平均值 (C++代码)浏览:1307 |
【魔板】 (C++代码)(时间超限,希望会的帮我改正一下)浏览:804 |
printf基础练习2 (C语言代码)浏览:796 |
求圆的面积 (C语言代码)浏览:1756 |
C语言训练-亲密数 (C语言代码)浏览:697 |
printf基础练习2 (C语言代码)浏览:653 |
IP判断 (C语言代码)浏览:592 |