You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改单个节点出边以构造全节点单环的编程问题:代码无法通过全部测试,寻求排查帮助

修改单个节点出边以构造全节点单环的编程问题:代码无法通过全部测试,寻求排查帮助

我现在正在尝试解决这个编程任务:

At New Year students play Secret Santa. Each student i is given a student a_i to 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 student 1 to student a_1, then and so on, then the chain will close with the student 1 after 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 one a_i number 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 12:24:31