[POJ 1351] Number of Locks

Number of Locks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 1326 Accepted: 642

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

    #include<algorithm> 
    #include<cstdio>
    #include<cmath>
    #include<iostream>
    #include<cstring>
    int n;  

    long long dp[18][5][2][4];  

    //a用二进制表示 0001表示有一种高度 0010表示有两种高度 
    long long dfs(int s,int h,int f,int c,int a)  
    {  
        if(s>=n)  
        {  
            if(f&&c>=3)  
                return 1;  
            else return 0;  
        }  
        if(dp[s][h][f][c]!=-1) return dp[s][h][f][c];  
        int t;  
        long long ans=0;  
        for(int i=1;i<=4;i++)  
        {  
            //如果第i种高度没有设置,如当前有两种高度, 
            //则在搜索下一个槽的时候加一种高度 
            t=(a&(1<<(i-1)))?c:(c+1);  
            t=(t>3)?3:t;  
            ans+=dfs(s+1,i,(h&&abs(i-h)==3)||f,t,a|(1<<(i-1)));  
        }  
        dp[s][h][f][c]=ans;  
        return ans;  
    }  
    int main()  
    {  
        while(scanf("%d",&n)&&(n!=-1))  
        {  
            memset(dp,-1,sizeof(dp));  
            dfs(0,0,0,0,0);  
            printf("%d: %lld\n",n,dp[0][0][0][0]);  
        }  
        return 0;  
    }  

你可能感兴趣的:(dp,poj)