HDU 3091 Necklace (狀態壓縮dp)


Necklace Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 327680/327680 K (Java/Others)
Total Submission(s): 658    Accepted Submission(s): 217


Problem Description
One day , Partychen gets several beads , he wants to make these beads a necklace . But not every beads can link to each other, every bead should link to some particular bead(s). Now , Partychen wants to know how many kinds of necklace he can make.
 

Input
It consists of multi-case . 
Every case start with two integers N,M ( 1<=N<=18,M<=N*N )
The followed M lines contains two integers a,b ( 1<=a,b<=N ) which means the ath bead and the bth bead are able to be linked.
 

Output
An integer , which means the number of kinds that the necklace could be.
 

Sample Input
3 3 1 2 1 3 2 3
 

Sample Output
2
 

Source
題意:給你一些珠子,這些珠子有編號,然後給可以相鄰的珠子的編號,把他們全部串起來有多少種方案。狀態壓縮,dp(i, j),i表示當前集合狀態爲i最後一個爲j的方案數,由於有重複的,我們固定起點爲1的方案數,然後枚舉其他不在當前集合的珠子狀態轉移,不過按照樣例,1-2-3-1,和1-3-2-1是不同的情況。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstring>
#include<map>
#include<set>
#include<queue>
#include<stack>
using namespace std;
const int N = (1<<18) + 10;
const double eps = 1e-10;
typedef long long ll;
ll dp[N][20];
int Map[20][20];
int main()
{
    int n, m;
    while(~scanf("%d%d", &n, &m))
    {
        memset(Map, 0, sizeof(Map));
        memset(dp, 0, sizeof(dp));
        int u, v;
        while(m--)
        {
            scanf("%d%d", &u, &v);
            Map[u][v] = Map[v][u] = 1;
        }
        dp[1][1] = 1;
        int num = (1<<n) - 1;
        for(int i = 1; i<=num; i++)
        {
            for(int j = 1; j<=n; j++)
            {
                if(!dp[i][j])
                    continue;
                for(int k = 1; k<=n; k++)
                {
                    if(!Map[j][k] || (i & (1<<(k-1))) || !(i & (1<<(j-1))))
                        continue;
                    dp[i|(1<<(k-1))][k] += dp[i][j];
                }
            }
        }
        ll ans = 0;
        for(int i = 1; i<=n; i++)
            if(Map[1][i])
                ans += dp[num][i];
        cout<<ans<<endl;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章