本文共 1094 字,大约阅读时间需要 3 分钟。
为了解决这个问题,我们需要将n名演员按n的所有约数d进行分组,每组形成一个环。每个环中相邻演员的衣服颜色不能相同,颜色有26种(a-z)。我们需要为每个演员分配颜色,如果颜色不够,输出“impossible”。
import mathdef get_divisors(n): divisors = set() for i in range(1, int(math.isqrt(n)) + 1): if n % i == 0: divisors.add(i) divisors.add(n // i) return sorted(divisors)n = int(input())divisors = get_divisors(n)m_max = 0for d in divisors: m = n // d if m > m_max: m_max = mif m_max > 26: print("impossible")else: colors = [0] * n for d in divisors: m = n // d for i in range(m): pos = i * d + 1 colors[pos - 1] = i + 1 for c in colors: print(c) 通过这种方法,我们可以确保每个环中相邻演员颜色不同,并且使用最少的颜色数。
转载地址:http://rbth.baihongyu.com/