用自创的算法快速解决拉姆奇数

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(coloru == colorv 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")

相关推荐
学无止境小袁同学10 小时前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴11 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
LK_0711 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk55511 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
用户548178459095012 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
yiangL_13 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
高洁0113 小时前
世界模型的因果内核:从预测表象到理解机制
人工智能·python·深度学习·transformer·迁移学习
数字融合14 小时前
透明化视频动态三维重建空间数据零核心技术
人工智能·python·virtualenv
AI创界者14 小时前
Python 进阶实战(五十四章):大模型推理网关终极架构——分布式全局前缀 Trie 缓存同步与多网关高可用协同调度
人工智能·python·aigc