题目描述:点击打开链接
题目大意:
有一些骑士要开圆桌会议,要求每次会议都满足以下条件:
1、开会的人数是奇数。
2、坐在相邻位置的两个人不能有仇恨。
3、开会人数不能为一人。
给出有仇恨骑士的名单,问有几个骑士永远不能参加会议。
思路:
1、求出原图的补图,即哪些骑士没有矛盾的图。
2、用tarjan算法求出点双联通分量。
3、用二分图染色判断奇圈。
在用tarjan算法求双联通分量时,要注意存储边,因为同一个点可以在多个双连通分量中,所以不能存储点。
还要注意,原图求补图后可能不连通了,要从多个点开始dfs,保证遍历到了图的每一个点。
打印时,不能直接打印不是奇圈的双连通分量中的节点数之和,还是因为双连通分量中的点有重复,应先记下来再打印总数。
代码:
#include<cstdio>
#include<iostream>
#include<map>
#include<vector>
using namespace std;
int n,m; //原图的点数和边数
bool a[1005][1005]= {0}; //补图的临接矩阵
int ans=0; //删除人数
struct E { //边
int x,y;
E() {
}
E(int xx,int yy) {
x=xx;
y=yy;
}
};
bool operator < (const E& A,const E& B) { //定义小于运算符
if(A.x<B.x) {
return true;
}
if(A.x==B.x&&A.y<B.y) {
return true;
}
return false;
}
E stack[1005]; //栈
int top=0;
map<E,int> instack; //判重以及记录该边在栈中的位置
vector<E> bcc[1005]; //双连通分量
int s_bcc=0;
int dfn[1005]= {0},low[1005]= {0};
int clock=0;
int tarjan(int x,int fa) { //tarjan算法求双联通分量
dfn[x]=low[x]=++clock;
bool flag=false;
for(int i=1; i<=n; i++) {
if(a[x][i]&&i!=fa) {
if(dfn[i]==0) {
stack[++top]=E(x,i);
instack[E(x,i)]=top;
int y=tarjan(i,x);
low[x]=min(low[x],y);
if(y>=dfn[x]) {
flag=true;
s_bcc++;
for(int j=instack[E(x,i)]; j<=top; j++) {
bcc[s_bcc].push_back(stack[j]);
}
top=instack[E(x,i)]-1;
}
} else if(dfn[i]<dfn[x] &&low[x]>dfn[i]) {
low[x]=dfn[i];
}
}
}
if(fa==0&&flag==false){
bcc[++s_bcc].push_back(E(fa,x));
}
return low[x];
}
int color[1001]= {0}; //颜色
vector<int> node; //该连通分量中的节点
bool use[1001]= {0}; //判重
bool dfs(int x,int y,int fa) { //二分图染色
use[x]=true;
color[x]=y;
for(int i=0; i<node.size(); i++) {
if(a[x][node[i]]&&node[i]!=fa) {
if(use[node[i]]==false) {
if(!dfs(node[i],3-y,x)){
return false;
}
} else if(color[node[i]]!=3-y) {
return false;
}
}
}
return true;
}
int main() {
while(true) {
scanf("%d%d",&n,&m);
if(n==0&&m==0) {
break;
}
top=0;
s_bcc=0;
ans=0;
clock=0;
instack.clear();
for(int i=1; i<=n; i++) {
bcc[i].clear();
dfn[i]=0;
low[i]=0;
for(int j=1; j<=n; j++) { //求补图
if(i!=j)
a[i][j]=true;
}
}
for(int i=1; i<=m; i++) {
int x,y;
scanf("%d%d",&x,&y);
a[x][y]=a[y][x]=false;
}
for(int i=1; i<=n; i++) { //从多个点出发求双连通分量
if(dfn[i]==0) {
tarjan(i,0);
}
}
bool Accept[1001]= {0};
for(int i=1; i<=s_bcc; i++) {
node.clear();
for(int j=1; j<=n; j++) {
use[j]=false;
}
map<int,bool> vx;
int s=0;
for(int j=0; j<bcc[i].size(); j++) { //取出连通分量中的节点
if(!vx.count(bcc[i][j].x)&&bcc[i][j].x!=0) {
s++;
vx[bcc[i][j].x]=true;
color[bcc[i][j].x]=0;
node.push_back(bcc[i][j].x);
}
if(!vx.count(bcc[i][j].y)&&bcc[i][j].y!=0) {
s++;
vx[bcc[i][j].y]=true;
color[bcc[i][j].y]=0;
node.push_back(bcc[i][j].y);
}
}
if(!dfs(bcc[i][0].x,1,0)) { //判奇圈
for(int j=0; j<node.size(); j++) {
Accept[node[j]]=true;
}
}
}
for(int i=1;i<=n;i++){ //输出
if(Accept[i]==false){
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}