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

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

相关推荐
Y幽谷客7 小时前
Python加载本地大模型(Qwen3.5 8B)
python·大模型
伞伞悦读8 小时前
【第36期】Python 目录与路径详解:pathlib、文件遍历、创建、复制、移动和删除风险
开发语言·python
线上放牧人8 小时前
Windows删除图标缓存
windows·python·pyqt
qq_5470261798 小时前
Python 变量和简单数据类型
python
智搜广告10 小时前
智搜广告:科技行业AI回答优化公司如何破局
大数据·python·elasticsearch·geo
IpdataCloud10 小时前
AI智能体调用工具怎么核验来源IP?归属地、网络类型与代理风险识别(含Python代码)
数据库·python·tcp/ip
2601_9669496510 小时前
只拿到股票代码还不够:量化程序到底还需要哪些标的信息?——从数据建模开始理解股票元数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
蒸鱼Yuzheng10 小时前
Python 游戏测试开发怎么准备:日志解析、接口校验、并发与可维护性
自动化测试·python·测试开发·面试题·游戏测试
Ivanqhz11 小时前
BM1688 双核架构
python·深度学习·神经网络·cnn·mlir
Java后端的Ai之路11 小时前
Python进阶探索17 - Python中的深拷贝与浅拷贝
人工智能·python·ai·浅拷贝·深拷贝