Number of Locks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 1434 | Accepted: 697 |
Description
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
Source
题意:用1~4组成N个数字,要求至少用到3种数字,且至少一对相邻数字差值为3。
思路:记忆化搜索基础题,dp记录第几个数,用了哪些数,是否有相邻的1与4,上一个数字。
# include <iostream>
# include <cstdio>
# include <cstring>
using namespace std;
typedef long long LL;
int n, num[18];
LL dp[18][1<<4][2][5];
LL dfs(int cur, int sta, int ok2, int pre)
{
if(cur == n)
{
if(num[sta]>=3 && ok2) return 1;
else return 0;
}
if(dp[cur][sta][ok2][pre] != -1) return dp[cur][sta][ok2][pre];
LL tmp = 0;
for(int i=1; i<=4; ++i)
{
int nok2=0, nsta=(1<<(i-1));
if((pre == 4 && i == 1) || (pre == 1 && i == 4)) nok2 = 1;
tmp += dfs(cur+1, sta|nsta, ok2||nok2, i);
}
return dp[cur][sta][ok2][pre] = tmp;
}
int main()
{
for(int i=0; i<(1<<4); ++i) num[i] = __builtin_popcount(i);
while(~scanf("%d",&n) && n != -1)
{
memset(dp, -1, sizeof(dp));
printf("%d: %lld\n",n,dfs(0,0,0,0));
}
return 0;
}