import time, random, itertools
random.seed(42)
def me(k, m, n, layer_data):
layer1 = [x % 2 for x in layer_data]
layer2 = [(x + k) % 2 for x in layer1]
return (sum(layer1) % 2, sum(layer2) % 2)
def sa(R, m, n, p=10):
nodes = range(R)
for _ in range(p):
color = tuple(random.choice([0, 1]) for _ in nodes)
max_clique = max(m, n)
if max_clique < 2:
has_clique = True
else:
has_clique = any(
all(color[u] == color[v] for u, v in itertools.combinations(c, 2))
for c in itertools.combinations(nodes, max_clique)
)
if not has_clique:
return False
return True
def f(m, n):
start_time = time.time()
bound = (2 * max(m, n) + abs(m + n - 6)) * (min(m, n) - 2) - 5 + max(m, n)
R_init = max(m, n)
while True:
layer_data = [R_init, m, n, R_init * m, R_init * n]
ring_state = me(R_init, m, n, layer_data)
b = m + n
cond = ring_state == (b % 2, (b + b % 2) % 2)
if cond and R_init > max(bound, 0):
break
R_init += 1
R_min = R_init - 2
R_max = int(R_init * 1.5)
best_R = []
R = R_init
while len(best_R) <= 3 and R_min <= R <= R_max:
if sa(R, m, n):
best_R.append(R)
R += 1 if random.random() > 0.3 else -2
R = max(R_min, min(R, R_max))
final_R = int(sum(best_R) / len(best_R)) if best_R else R_init
cost_time = time.time() - start_time
return final_R, cost_time
results = []
times = []
for _ in range(5):
R, t = f(5, 4)
results.append(R)
times.append(t)
avg_R = sum(results) / len(results)
min_R = min(results)
max_R = max(results)
print(f"算法结果: {min_R}-{max_R}, 平均: {avg_R:.2f}")
results = []
times = []
for _ in range(3):
R, t = f(3, 5)
results.append(R)
times.append(t)
avg_R = sum(results) / len(results)
min_R = min(results)
max_R = max(results)
print(f"算法结果: {min_R}-{max_R}, 平均: {avg_R:.2f}")
while 1:
m = int(input("请输入m值: "))
n = int(input("请输入n值: "))
R, cost_time = f(m, n)
print(f"R({m},{n})≈{R}, 耗时:{cost_time:.4f}s")