Necklace
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 327680/327680 K (Java/Others)Total Submission(s): 379 Accepted Submission(s): 120
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.
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
Recommend
lcy
简单的状态dp。
跟TSP问题差不多。
代码
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
vector <int> a[20];
long long dp[(1<<18)+6][20];
int main()
{
int i,j,n,t,x,y,k,tag,p;
long long ans;
while(scanf("%d%d",&n,&t)!=EOF)
{
for (i=0;i<n;i++)
{
a[i].clear();
}
while(t--)
{
scanf("%d%d",&x,&y);
x--;y--;
a[x].push_back(y);
a[y].push_back(x);
}
memset(dp,0,sizeof(dp));
dp[1][0]=1;
for (i=1;i<(1<<n);i++)
{
for (j=0;j<n;j++)
{
if (dp[i][j]==0) continue;
for (k=0;k<a[j].size();k++)
{
tag=a[j][k];
if ((i & (1<<tag))!=0) continue;
p=(i | (1<<tag));
dp[p][tag]+=dp[i][j];
}
}
}
ans=0;
for (i=0;i<a[0].size();i++)
{
ans+=dp[(1<<n)-1][a[0][i]];
}
printf("%I64d\n",ans);
}
return 0;
}