1.正则问题
import os
import sys
s=list(input())
pos=0
max_len=len(s)
def dfs(): # 判断当前()最多有多少个x
global pos,max_len
ok,tmp=0,0
while pos<max_len:
if s[pos]=='(':
pos+=1
tmp=tmp+dfs()
elif s[pos]=='x':
pos+=1
tmp=tmp+1
elif s[pos]=='|':
pos+=1
ok=max(ok,tmp)
tmp=0
elif s[pos]==')':
pos+=1
return max(ok,tmp)
return max(ok,tmp)
print(dfs())
2. 寒假作业
这道题可以用排列组合解决,但是严重超时:
from itertools import permutations
a=[i for i in range(1,14)]
ok = permutations(a)
result = 0
def check(x):
if x[0]+x[1]==x[2] and x[3]-x[4]==x[5] and x[6]*x[7]==x[8] and x[9]//x[10]==x[11]:
return 1
return 0
for item in ok:
result += check(item)
print(result)
dfs+剪枝可以代替排列:
a=[0 for i in range(15)]
vis=[0 for i in range(15)]
ok = 0
def dfs(num):
global ok
if num==13:
if a[10]==a[12]*a[11]:
ok = ok + 1
return
if num==4:
if a[1]+a[2]!=a[3]:
return
if num==7:
if a[4]-a[5]!=a[6]:
return
if num==10:
if a[7]*a[8]!=a[9]:
return
for i in range(1,14):
if vis[i]==0:
a[num]=i
vis[i]=1
dfs(num+1)
vis[i]=0
dfs(1)
print(ok)
正确答案为64