您的位置:首页 > 其它

UVA - 10004 Bicoloring(判断二分图——交叉染色法 / 带权并查集)

2016-01-29 21:08 531 查看
d.给定一个图,判断是不是二分图。

s.可以交叉染色,就是二分图;否则,不是。

另外,此题中的图是强连通图,即任意两点可达,从而dfs方法从一个点出发就能遍历整个图了。

如果不能保证从一个点出发可以遍历整个图,那么编程要注意了,应该从每个点出发遍历一次。

s2.带权并查集来判断,略复杂。先略过。先上个博客:http://blog.csdn.net/zsc09_leaf/article/details/6727622

c.邻接矩阵,bfs

#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;

#define MAXN 205//点数
#define MAXM 10000//边数

int color[MAXN];

struct Edge{
int to,next;
}edge[MAXM];

int head[MAXN];
int tot;

void addedge(int u,int v){
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
}

void init(){
tot=0;
memset(head,-1,sizeof(head));
}

bool dfs(int u){//dfs交叉染色,两种颜色标记为 1 和 -1,未染色标记为 0

int v;

for(int i=head[u];i!=-1;i=edge[i].next){

v=edge[i].to;

if(color[v]==0){//未染色
if(color[u]==1){
color[v]=-1;
}
else{
color[v]=1;
}

if(!dfs(v)){//不能交叉染色
return false;
}
}
else{//已染色
if(color[v]==color[u]){//不能交叉染色
return false;
}
}

}
return true;
}

int main(){

int n,L;
int u,v;

while(~scanf("%d",&n)){
if(n==0)break;

memset(color,0,sizeof(color));
init();

scanf("%d",&L);

for(int i=0;i<L;++i){
scanf("%d%d",&u,&v);

addedge(u,v);
addedge(v,u);
}

color[0]=1;
if(dfs(0)){
printf("BICOLORABLE.\n");
}
else{
printf("NOT BICOLORABLE.\n");
}
}

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: