https://www.hackerrank.com/challenges/candles-2/problem
https://www.hackerrank.com/challenges/candles-2/editorial
先不考虑color,DP复杂度是NN,从状态转移方程看到每次求dp[i]都有个求和的过程,这个可以用线段树优化,然后正好height数组也是有范围的。
然后就开始考虑color,一开始的思路就是用一个int表示color的枚举,枚举所有color的可能,但是怎么结合线段树有点卡住了,后来就换成了容斥原理:这样一定要有x样color就变成了从x样中选
bits=[0]*50001
dp=[0]*50001
mod=10**9+7
def query(i):
res=0
while i:
res+=bits[i]
i-=i&-i
return res
def add(i,x):
while i<len(bits):
bits[i]+=x
i+=i&-i
def candlesCounting(k, candles):
res,n=0,len(candles)
for mask in range(1<<k):
for i in range(50001): bits[i]=0
t=0
for i in range(n):
if not mask&(1<<(candles[i][1]-1)): continue
dp[i]=1+query(candles[i][0]-1)
t=(t+dp[i])%mod
add(candles[i][0], dp[i])
if bin(mask).count('1')%2==k%2:
res=(res+t)%mod
else:
res=(res-t)%mod
return res
if __name__ == '__main__':
nk = input().split()
n = int(nk[0])
k = int(nk[1])
candles = []
for _ in range(n):
candles.append(list(map(int, input().rstrip().split())))
result = candlesCounting(k, candles)
print(result)