Necklace
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2848 Accepted Submission(s): 879
Problem Description
SJX has 2*N magic gems.
N
of them have Yin energy inside while others have Yang energy. SJX wants to make a necklace with these magic gems for his beloved BHB. To avoid making the necklace too Yin or too Yang, he must place these magic gems Yin after Yang and Yang after Yin, which
means two adjacent gems must have different kind of energy. But he finds that some gems with Yang energy will become somber adjacent with some of the Yin gems and impact the value of the neckless. After trying multiple times, he finds out M rules of the gems.
He wants to have a most valuable neckless which means the somber gems must be as less as possible. So he wonders how many gems with Yang energy will become somber if he make the necklace in the best way.
Input
Multiple test cases.
For each test case, the first line contains two integers N(0≤N≤9),M(0≤M≤N∗N), descripted as above.
Then M lines followed, every line contains two integers X,Y, indicates that magic gem X with Yang energy will become somber adjacent with the magic gem Y with Yin energy.
For each test case, the first line contains two integers N(0≤N≤9),M(0≤M≤N∗N), descripted as above.
Then M lines followed, every line contains two integers X,Y, indicates that magic gem X with Yang energy will become somber adjacent with the magic gem Y with Yin energy.
Output
One line per case, an integer indicates that how many gem will become somber at least.
Sample Input
2 1 1 1 3 4 1 1 1 2 1 3 2 1
Sample Output
1 1
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <map>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
int n,m,ans;
bool mapp[10][10],vis[10][10],use[10];
int a[10],girl[10];
bool dfs(int x)
{
for(int i=1;i<=n;i++)
{
if(vis[i][x]&&!use[i])
{
use[i]=true;
if(girl[i]==0||dfs(girl[i]))
{
girl[i]=x;
return true;
}
}
}
return false;
}
int hungary()
{
int res=0;
memset(girl,0,sizeof(girl));
for(int i=1;i<=n;i++)
{
memset(use,false,sizeof(use));
if(dfs(i))
res++;
}
return res;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0)
{
printf("0\n");
continue;
}
memset(mapp,false,sizeof(mapp));
while(m--)
{
int x,y;
scanf("%d%d",&x,&y);
mapp[x][y]=true;
}
ans=INF;
for(int i=1;i<=n;i++)
a[i]=i;
do
{
memset(vis,false,sizeof(vis));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(!mapp[i][a[j]]&&!mapp[i][a[j%n+1]])//检查这个时候两边是否都可以放
vis[i][j]=true;
}
ans=min(ans,n-hungary());//n-最大排列,就是最少染色的数量
}while(next_permutation(a+2,a+n+1));//因为是个环,所以只需要全排列(n-1)个数就好,少了一个*n的复杂度
printf("%d\n",ans);
}
return 0;
}