hdu 5727 Necklace dfs+二分图匹配
Necklace/center>
题目连接:
http://acm.hdu.edu.cn/showproblem.php?pid=5727
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.Given four points ABCD, if ABCD is a tetrahedron, calculate the inscribed sphere of ABCD.
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.
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
Hint
题意
你有2n个珠子,每种珠子都有阴阳两种,你需要弄成一个环形的且阴阳交替的链。
然后给你M条边a,b。表示如果a阳球靠近了b阴球,那么阳球A就会暗淡。
让你输出构造一条链,使得暗淡的阳珠子最少。
题解:
dfs枚举阴珠子的排列,然后再二分图匹配跑阳珠子。
如果i位置能放j阳球
那么建一条j->i,流量为1的边
然后跑就好了。
但是我写的太渣了,会TLE,就随手加了个只搜10000次的剪枝。
然后就过了,蛤蛤蛤。
代码
#include<bits/stdc++.h>
using namespace std;
int vis[12];
int Vis[12];
int mp[12][12];
int n,m;
int ans;
int kkk[12];
vector<int> q[12];
int match[12];
int Dfs(int x){
for(int i=0;i<q[x].size();i++)
{
if(Vis[q[x][i]]==0)
{
Vis[q[x][i]]=1;
if(match[q[x][i]]==-1||Dfs(match[q[x][i]]))
{
match[q[x][i]]=x;
return 1;
}
}
}
return 0;
}
int QAQ(){
for(int i=0;i<n;i++)q[i].clear(),match[i]=-1;
for(int i=0;i<n;i++){
for(int j=1;j<=n;j++){
if(!mp[j][kkk[i]]&&!mp[j][kkk[(i-1+n)%n]]){
q[i].push_back(j-1);
}
}
}
int tmp = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)Vis[j]=0;
if(Dfs(i))tmp++;
}
return n-tmp;
}
int cnt = 0;
void dfs(int x){
cnt++;
if(cnt>100000)return;
if(x==n){
ans=min(ans,QAQ());
return;
}
for(int i=1;i<=n;i++){
if(!vis[i]){
vis[i]=1;
kkk[x]=i;
dfs(x+1);
kkk[x]=0;
vis[i]=0;
}
}
}
void solve(){
cnt=0;
ans=100;
memset(mp,0,sizeof(mp));
for(int i=1;i<=m;i++){
int a,b;
scanf("%d%d",&a,&b);
mp[a][b]=1;
}
dfs(0);
cout<<ans<<endl;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
solve();
}
return 0;
}