sevenzero liked Warcraft very much, but he haven't practiced it for several years after being addicted to algorithms. Now, though he is playing with computer, he nearly losed and only his hero Pit Lord left. sevenzero is angry, he decided to cheat to turn defeat into victory. So he entered "whosyourdaddy", that let Pit Lord kill any hostile unit he damages immediately. As all Warcrafters know, Pit Lord masters a skill called Cleaving Attack and he can damage neighbour units of the unit he attacks. Pit Lord can choice a position to attack to avoid killing partial neighbour units sevenzero don't want to kill. Because sevenzero wants to win as soon as possible, he needs to know the minimum attack times to eliminate all the enemys.
5 4 1 2 1 3 2 4 4 5 6 4 1 2 1 3 1 4 4 5
2
3
题意:大战一触即发,有n个敌人需要消灭,这里有m个关系(a,b)表示a,b相邻,题意是当你命中一个敌人时,与他相邻的敌人也被打死,问最少需要打死几个敌人才能把敌人全部消灭
思路:构造0—1矩阵,用舞蹈链,这里n个数代表n列,而每个数则代表一行,两个数相邻,咋把该行对应的位置变为1
ac代码:
#include <vector>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3fll;
const int maxn=60;
int L[maxn*maxn],R[maxn*maxn],U[maxn*maxn],D[maxn*maxn];//节点的上下左右四个方向的链表
int C[maxn*maxn],H[maxn],cnt[maxn],vis[maxn];//C列H行cnt列链表中元素个数
int n,m,id,fans;
vector<int>G[maxn];
void init(){
for(int i=0;i<=n;i++){
G[i].clear();
G[i].push_back(i);
cnt[i]=0;U[i]=D[i]=i;
L[i+1]=i;R[i]=i+1;
}
R[n]=0;id=n+1;
memset(H,-1,sizeof(H));
}
void Link(int r,int c){
cnt[c]++;C[id]=c;
U[id]=U[c];D[U[c]]=id;
D[id]=c;U[c]=id;
if(H[r]==-1) H[r]=L[id]=R[id]=id;
else{
L[id]=L[H[r]];R[L[H[r]]]=id;
R[id]=H[r];L[H[r]]=id;
}
id++;
}
void Remove(int Size){
for(int j=D[Size];j!=Size;j=D[j])
L[R[j]]=L[j],R[L[j]]=R[j];
}
void Resume(int Size){
for(int j=D[Size];j!=Size;j=D[j])
L[R[j]]=R[L[j]]=j;
}
int h()
{
int sum=0;
memset(vis,0,sizeof(vis));
for(int i=R[0];i;i=R[i]){
if(vis[i]) continue;
sum++;
for(int j=D[i];j!=i;j=D[j]){
for(int k=R[j];k!=j;k=R[k])
vis[C[k]]=1;
}
}
return sum;
}
void Dance(int k){
int mm=maxn,pos;
if(k+h()>=fans) return;
if(!R[0]){
if(k<fans) fans=k;
return;
}
for(int i=R[0];i;i=R[i])
if(mm>cnt[i]) mm=cnt[i],pos=i;
for(int i=D[pos];i!=pos;i=D[i])
{
Remove(i);
for(int j=R[i];j!=i;j=R[j]) Remove(j);
Dance(k+1);
for(int j=R[i];j!=i;j=R[j]) Resume(j);
Resume(i);
}
}
int main(){
int u,v;
while(scanf("%d%d",&n,&m)!=-1){
init();
for(int i=0;i<m;i++){
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=n;i++){
for(int j=0;j<G[i].size();j++){
int t=G[i][j];
Link(i,t);
}
}
fans=n;
Dance(0);
printf("%d\n",fans);
}
return 0;
}