您的位置:首页 > 其它

hdu 5727 Necklace (全排列+二分匹配)

2016-07-21 10:39 423 查看
[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
  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.

 

[align=left]Output[/align]
One line per case, an integer indicates that how many gem will become somber at least.
 

[align=left]Sample Input[/align]

2 1
1 1
3 4
1 1
1 2
1 3
2 1

 

[align=left]Sample Output[/align]

1
1
题意:给你2*n颗宝石,其中n颗阳宝石,n颗阴宝石,让你阴阳间隔串在项链上(围成一个环),还给你了m对x,y,表示如果阳宝石x和阴宝石y挨在一起,阳宝石就会受影响,让你求出阳宝石受影响的最少数量。暴力解法:我们可以用全排列先枚举阴宝石的所有放法,让后看每两个阴宝石中间放哪些阳宝石而不受影响,那么我们可以对每个空位编号从1-n,这个空位编号向对应阳宝石编号连边,注意最后一个阴宝石和第一个阴宝石也要算进去,然后跑最大二分匹配,求出未匹配点数就可以更新答案,如果矩阵存图会超时,换邻接表就行。
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
bool no[20][20];
int maze[20][20];
int a[20];
int n,m;
int cnt,p[20];
struct node
{
int v,next;
}E[1000];
void add(int u,int v)
{
E[cnt].v=v;
E[cnt].next=p[u];
p[u]=cnt++;
}
int fg[20];
int pp[20];
bool Find(int x)
{
for(int i=p[x];i!=-1;i=E[i].next)
{
int y=E[i].v;
if(!fg[y])
{
fg[y]=1;
if(pp[y]==0||Find(pp[y]))
{
pp[y]=x;
return 1;
}
}
}
return 0;
}
int solve()
{
int ans=0;
for(int i=1;i<=n;i++) pp[i]=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++) fg[i]=0;
if(Find(i)) ans++;
}
return ans;
}
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
no[i][j]=false;
for(int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
no[y][x]=true;
}
if(m==0)
{
puts("0");
continue;
}
for(int i=1;i<=n;i++) a[i]=i;
int ans=20;
do
{
cnt=0;
for(int i=1;i<=n;i++) p[i]=-1;
for(int i=1;i<n;i++)
for(int j=1;j<=n;j++)
if(!no[a[i]][j]&&!no[a[i+1]][j]) add(i,j);
for(int j=1;j<=n;j++)
if(!no[a[1]][j]&&!no[a
][j]) add(n,j);
ans=min(ans,n-solve());
if(ans==0) break;
}while(next_permutation(a+1,a+n+1));
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: