修改单个节点出边以构造全节点单环的编程问题:代码无法通过全部测试,寻求排查帮助
我现在正在尝试解决这个编程任务:
At New Year students play Secret Santa. Each student
iis given a studenta_ito whom they must give a gift. The administrator of the game assigned each student their own number. But then his colleague asked: Is it true that if you start a chain of gifts from student1to studenta_1, then and so on, then the chain will close with the student1after it has involved all the other students exactly once? The administrator doesn’t know whether this is true or not, but he is going to change exactly onea_inumber to get a configuration that will suit his colleague. Help him with this.
输入输出说明
- 输入:
- 第一行是自然数
n(范围2 <= n <= 10^5)—— 学生的总数量 - 第二行是
n个整数a_i(范围1 <= a_i <= n)—— 编号为i的学生要赠送礼物的对象编号
- 第一行是自然数
- 输出:
- 输出两个整数
x和y(1 <= x, y <= n且x != y):x是需要修改出边的学生编号,y是修改后的a_x值,注意修改后的y不能等于原来的a_x。如果有多个合法答案,输出任意一个即可 - 如果无法通过修改恰好一条边达成目标,输出
-1 -1
- 输出两个整数
示例
示例1
输入:
3 1 2 3
输出:
-1 -1
示例2
输入:
3 1 3 1
输出:
1 2
我的代码
我写了下面这段Python代码来解决这个问题:
n = int(input()) students = [int(x) for x in input().split()] a, b = -1, -1 for x in range(1, n + 1): d = [x] vals = set() vals.add(x) for i in range(1, n + 1): val = students[d[i - 1] - 1] d.append(val) if val in vals: break vals.add(val) # print(f'x = {x} | d = {d}') if len(set(d)) == n: if d[-1] != d[0]: a = d[-2] b = d[0] print(a, b)
我的思路与问题
我理解这个问题本质上是判断当前的有向图(每个节点对应一个学生,出边对应送礼物的对象)是否只需要修改一条边,就能变成一个包含所有节点的单环(也就是哈密顿环)。
我自己测试了几个案例,代码都能给出正确结果,但它没办法通过所有的测试用例。有没有人能帮我排查一下问题出在哪里?提前感谢大家的帮助!
备注:内容来源于stack exchange,提问作者Alisa Petrova

