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

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")

相关推荐
爱吃羊的老虎21 分钟前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python
小桥流水---人工智能1 小时前
【已解决】ImportError: cannot import name ‘AdamW‘ from ‘transformers.optimization‘
python
芝麻开门GEO1 小时前
泰安GEO优化服务,真的能提升效果吗?
人工智能·python
颜酱1 小时前
选读:工业级调用 LangChain:从 Demo 到企业级应用
python
颜酱2 小时前
LangChain 调用大模型实战:从跑通到服务商与模型选型
python·langchain
唐装鼠2 小时前
Nginx + Gunicorn + Python Web 应用 架构(Claude)
python·nginx·gunicorn
梦想三三2 小时前
【PYthon词频统计与文本向量化】苏宁易购评论分析实战
开发语言·python
biter down3 小时前
9:JSONSchema
python
日晨难再3 小时前
C语言&Python&Bash&Tcl:全局变量和局部变量
c语言·python·bash·tcl
麻雀飞吧3 小时前
期货量化主连和具体合约怎么切:天勤 KQ.m 与 KQ.i 用法
python·区块链