Problem
In certain factory a kind of spring locks is manufactured. There are n slots (1 < n < 17, n is a natural number.) for each lock. The height of each slot may be any one of the 4 values in{1,2,3,4}( neglect unit ). Among the slots of a lock there are at least one pair of neighboring slots with their difference of height equal to 3 and also there are at least 3 different height values of the slots for a lock. If a batch of locks is manufactured by taking all over the 4 values for slot height and meet the two limitations above, find the number of the locks produced.
Input
There is one given data n (number of slots) on every line. At the end of all the input data is -1, which means the end of input.
Output
According to the input data, count the number of locks. Each output occupies one line. Its fore part is a repetition of the input data and then followed by a colon and a space. The last part of it is the number of the locks counted.
Sample Input
2
3
-1
Sample Output
2: 0
3: 8
分析:
状压dp.
用d[i][j][k][f]表示前i个插槽,上一个钥匙是j,当前包含集合k,是否已经有差值为3的相邻槽,的方案数.
对于d[i][j][k][f],枚举下一个选择的钥匙进行转移即可.
code:
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
#define ll long long
ll d[20][20][20][2];
int n;
int cal(int x){
int ans=0;
while(x){
if(x&1)ans++;
x>>=1;
}
return ans;
}
int main(){
while(cin>>n&&n!=-1){
const int p=4;
memset(d,0,sizeof d);
for(int i=0;i<p;i++){
d[1][i][(1<<i)][0]=1;
}
for(int i=1;i<n;i++){
for(int j=0;j<p;j++){
for(int k=0;k<(1<<p);k++){
for(int f=0;f<2;f++){
if(!d[i][j][k][f])continue;
for(int now=0;now<p;now++){
int t=f;
if(abs(now-j)==3)t=1;
d[i+1][now][k|(1<<now)][t]+=d[i][j][k][f];
}
}
}
}
}
ll ans=0;
for(int j=0;j<p;j++){
for(int k=0;k<(1<<p);k++){
if(!d[n][j][k][1])continue;
if(cal(k)>=3)ans+=d[n][j][k][1];
}
}
cout<<n<<": "<<ans<<endl;
}
return 0;
}