python求助

P1088 [NOIP2004 普及组] 火星人

只过了样例和测试#1,十分
by asdfjkd @ 2024-03-05 11:04:16


```python n = int(input()) m = int(input()) lists = list(map(int, input().split())) sum = 0 vis = [1 for i in range(n)] ans = [0 for i in range(n)] def dfs(num): global sum if num>n: sum += 1 if sum == 1+m: print(' '.join('%d'%o for o in ans),end='') return else: for i in lists: if vis[lists.index(i)]: if sum == 1+m: return vis[lists.index(i)] = 0 ans[num-1] = i dfs(num+1) vis[lists.index(i)] = 1 dfs(1) 更新,30分,#1,#3,#6,lists列表不用排序
by asdfjkd @ 2024-03-05 19:48:50


```python import itertools n = int(input()) num = int(input()) a = list(map(int, input().split())) normal = sorted(a.copy()) path = a.copy() def factorial(n): ans = 1 for i in range(1, n + 1): ans *= i return ans def dfs(depth, path, i): if depth == 0: print(' '.join(map(str, path))) return res = path[(n - i):n] items = sorted(res.copy()) permutation = list(itertools.permutations(items)) idx = permutation.index(tuple(res)) + 1 location = min((factorial(i) - idx), depth) path = path[:(n-i)] + list(permutation[idx + location - 1]) dfs(depth - location, path, i+1) dfs(num, path, 2) ``` # 我这个快一点吧,只有16毫秒,从2位开始找,依次找到对应的排列组合,如果全排的话就太慢了
by dracuxi @ 2024-03-06 22:57:09


我最大的疑问是用这种方法如何保证后续递归出来的序列字典序一定是递增的,我觉得应该是错在这里了,具体怎么改我没想到,我尝试最后循环出的序列和上一个序列的字典序进行比较,结果明显超时,看来应该在for循环里面进行剪枝,挺难想的
by dracuxi @ 2024-03-07 23:15:46


@[dracuxi](/user/945662) 非常感谢,今天看懂了 ```python import sys sys.setrecursionlimit(100000) #设置为十万 n = int(input()) num = int(input()) lists = list(map(int, input().split())) sum = 0 vis = [1 for i in range(n)] ans = [0 for i in range(n)] tem = "".join(map(str, lists)) def dfs(depth, tem): global sum if depth>n: ans_x = "".join(map(str, ans)) if ans_x > tem: tem = ans_x sum += 1 if sum == num: print(' '.join('%d'%o for o in ans),end='') return else: for i in lists: if vis[lists.index(i)]: vis[lists.index(i)] = 0 ans[depth-1] = i dfs(depth+1, tem) vis[lists.index(i)] = 1 dfs(1, tem) ``` 我照你说的改了一下,对大于上一个的排序进行保存,只有大于它sum才能加一,可深度太大了,很感谢前面的代码
by asdfjkd @ 2024-03-10 19:57:18


|