Day 3
听课。
重点在dp及dp优化上。
T1
JZOJ 5935
Description
由于小凯上次在找零问题上的疑惑,给大家在考场上带来了很大的麻烦,他决心好好学习数学
本次他挑选了位运算专题进行研究 他发明了一种叫做“小凯运算”的运算符:
a$b =( (a&b) + (a|b) )>>1
他为了练习,写了n个数在黑板上(记为a[i]) 并对任意相邻两个数进行“小凯运算”,把两数擦去,把结果留下 这样操作n-1次之后就只剩了1个数,求这个数可能是什么?
将答案从小到大顺序输出
Input
4
1 4 3 2
Output
1 2
Sample Input
4
1 4 3 2
Sample Output
1 2
Data Constraint
30% n<=10 0<=a[i]<=7
70% n<=150 0<=a[i]<=3
100% n<=150 0<=a[i]<=7
Solution
a$b=a+b>>1
于是有下列方程:
f[i][j][k]=f[i][l][p]&f[r][j][q] (i<=l<r<=j,p+q>>1=k)
其中f[i][j][k]表示在区间[i,j]中能不能表示k这个数。
复杂度
O
(
n
2
)
O(n^2)
O(n2)
Code
#include <cstdio>
#include <iostream>
const int N = 151;
const int M = 10;
int n,a[N];
bool f[N][N][M];
int main(){
freopen("math.in","r",stdin);
freopen("math.out","w",stdout);
scanf("%d",&n);
for(int i=1; i<=n; i++){
scanf("%d",&a[i]);
f[i][i][a[i]]=1;
}
for(int len=2; len<=n; len++){
for(int i=1; i<=n-len+1; i++){
int j=i+len-1;
for(int l=i; l<=j-1; l++){
for(int p=0; p<=7; p++){
for(int q=0; q<=7; q++){
int k=p+q>>1;
f[i][j][k]|=f[i][l][p]&f[l+1][j][q];
}
}
}
}
}
for(int i=0; i<=7; i++){
if(f[1][n][i]){
printf("%d ",i);
}
}
return 0;
}
斜率优化
把dp方程含某个不定未知数的移到一边,其他移到另一边,在可以使用斜率优化的题中,方程就会变成形如
y
=
k
x
+
b
y=kx+b
y=kx+b
的形式,对于这样的方程,我们可以进行进一步分析其最优情况有怎么样的单调性。