hdu5727
Necklace
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.
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 Ywith Yin energy.
Output
Sample Input
题意:
有2n(0<=n<=9)个珠子,分成阴阳两极,每极各n个。
用这2n个珠子做成一个项链,使得相邻两个珠子的极性是不一样的,因为有一些阳性的珠子会被一些阴性的珠子所削弱在它们它们相邻的情况下。
给你m(0<=m<=n*(n-1)/2)个关系[x,y]表示阳性珠子x会被阴性珠子y在相邻情况下所削弱。问你最少有多少个阳性被削弱。
题解:对阴珠全排列,插入阳珠这样可以枚举出两个珠子的位置,利用给的关系找出每种情况下珠子的互相作用关系,再利用二分图的最大匹配找到一个多大不消退。
#include <iostream> #include <stdio.h> #include <string.h> #define INF 0x3f3f3f3f using namespace std; const int N=20; int vis[N],a[N]; int n,m,ret; int mp[N][N],g[N][N],match[N],used[N]; bool dfs(int u){ for(int v=1;v<=n;++v){ if(!g[u][v]||used[v]) continue; used[v]=true; if(match[v]==-1||dfs(match[v])){ match[v]=u; return true; } } return false; } void solve(){ memset(match,-1,sizeof(match)); memset(g,0,sizeof(g)); for(int i=2;i<=n;++i){ for(int j=1;j<=n;++j){ if(mp[a[i]][j]||mp[a[i-1]][j]) continue; g[i][j]=true; //把珠子之间的关系做处理,褪色的两个珠子标记为0,不褪色的珠子为1,利用二分图最大匹配找到最大不消退数。 } } for(int i=1;i<=n;++i){ if(mp[a[1]][i]||mp[a[n]][i]) continue; g[1][i]=true; } int ans=0; for(int i=1;i<=n;++i){ memset(used,0,sizeof(used)); if(dfs(i))++ans; } ret=min(ret,n-ans); } void get(int x) { if(ret==0)return ; if(x==n+1) { solve();return ; } for(int i=1;i<=n;i++) { if(vis[i]) continue; vis[i]=1; a[x]=i; get(x+1); vis[i]=0; } } int main() { int v,u,i; vis[1]=1,a[1]=1; while(~scanf("%d%d",&n,&m)) { if(n==0) { printf("0\n"); continue; } memset(mp,0,sizeof(mp)); for(i=0;i<m;i++) { scanf("%d%d",&u,&v); mp[v][u]=1; } ret=INF; get(2);// n个阴珠子的全排列(注意:环形序列的全排列) printf("%d\n",ret); } return 0; }
题解:
我们可以先暴力枚举出所有阴性珠子的排列情况(因为是环,所以有(n-1)!种),然后在它们之间插入阳性的珠子,判断出阳性珠子插入在之间会不会被削弱。我们通过匈牙利算法算出最大匹配sum,然后算出n-sum,对于每种排列取最小值就得到了我们想要的答案,注意特判下n=0的情况。