利用DuckDB SQL求解集合数学题

已知集合I={1,2,3,4,5,6},A={(s,t)|s ∈I,t∈I},若B包含于A,且对任意的(a,b)∈B,(x,y)∈B,均有(a-x)(b-y)<=0,则集合B中元素个数的最大值是几?

sql 复制代码
set variable n=6;
with recursive i as(select i from range(1,getvariable('n')+1)t(i)),
a as(select 1::bigint<<((i1.i-1)*getvariable('n')+i2.i)m, i1.i s, i2.i t from i i1,i i2),
b as(select 1 lv,m,[(a,b),(x,y)]st from(select a.m+a1.m m,a.s a,a.t b,a1.s x,a1.t y from a,a a1 where a.m<a1.m) where (a-x)*(b-y)<=0 
union all
select lv+1,a.m+b.m,st +[(a.s,a.t)] from b,a where a.m>b.m /*and a.m & b.m=0*/ and not exists(select 1 from range(1,lv+2) un(nb) where (a.s-b.st[nb][1])*(a.t-b.st[nb][2])>0))
from b where lv=(select max(lv) from b);

求出的最大元素个数是11,一共有252个不同的集合满足要求。本来是需要用对二进制位与运算为0来判断的,但是由于低位全1也比高位1低位0的二进制数小,所以有了a.m>b.m,注释掉与运算判断也不影响结果。

也可以不用range笛卡尔积,而用unnest函数来实现,不过慢一点

sql 复制代码
set variable n=6;
with recursive i as(select i from range(1,getvariable('n')+1)t(i)),
a as(select 1::bigint<<((i1.i-1)*getvariable('n')+i2.i)m, i1.i s, i2.i t from i i1,i i2),
b as(select 1 lv,m,[(a,b),(x,y)]st from(select a.m+a1.m m,a.s a,a.t b,a1.s x,a1.t y from a,a a1 where a.m<a1.m) where (a-x)*(b-y)<=0 
union all
select lv+1,a.m+b.m,st +[(a.s,a.t)] from b,a where a.m>b.m and not exists(select 1 from unnest(b.st) un(nb) where (a.s-nb[1])*(a.t-nb[2])>0))
from b where lv=(select max(lv) from b);

比起python程序,SQL还是简练一点。

相关推荐
近津薪荼44 分钟前
优选算法——双指针4(单调性)
c++·学习·算法
啊吧怪不啊吧1 小时前
极致性能的服务器Redis之String类型及相关指令介绍
网络·数据库·redis·分布式·mybatis
zihan03211 小时前
Redis Windows版本默认配置文件,Redis配置不生效解决方案
数据库·redis·缓存
Hgfdsaqwr2 小时前
实战:用Python开发一个简单的区块链
jvm·数据库·python
砚边数影2 小时前
InfluxDB迁移替换实战:金仓时序数据库如何提高写入性能
数据库·性能优化·时序数据库·kingbase·kingbasees·金仓数据库
IUGEI2 小时前
从原理到落地:DAG在大数据SLA中的应用
java·大数据·数据结构·后端·算法
云深麋鹿2 小时前
五.排序笔记
c语言·数据结构·算法·排序算法
spcier8 小时前
图论拓扑排序-Kahn 算法
算法·图论
知星小度S8 小时前
动态规划(一)——思想入门
算法·动态规划
ysa0510308 小时前
动态规划-逆向
c++·笔记·算法