这道题目,我最开始的时候看了一遍没有看懂让做什么。
其实认真读体会在下面这段话里差不多看出让干些什么。
That is, if one can assign colors (from a palette of two) to the nodes in such a way that no two adjacent nodes have the same color. To simplify the problem you can assume:
-
no node will have an edge to itself.
-
the graph is nondirected. That is, if a node a is said to be connected to a node b, then you must assume that b is connected to a.
-
the graph will be strongly connected. That is, there will be at least one path from any node to any other node.
再结合样例输入和输出,就能知道题目大意。
做这道题的收获就是,看题目的时候要认真更要思考,这不是做英语阅读理解,你没有必要把所有的东西弄清楚,你只需要明确题目要让你去做什么,以及题目给出的一些可能成为陷阱的小细节。
回归本题,它的要求就是:
样例输入两个数a b,代表一条边的两个端点,并说明存在这么一条边。
然后会给出多组a b的组合,表示许多连通的边。
你的任务是判断能不能用两种颜色给这些点涂色,使得任意相邻的任意两个点的颜色都不相同。
若可以请输出:BICOLORABLE., 否则输出:NOT BICOLORABLE.
AC之后总结这道题的本质是,判断所给出的一个无向图,是不是所谓的二部图。
具体的细节问题可以看一下代码中的注释,很好理解:
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN=210;
bool node[MAXN][MAXN];
bool vis[MAXN];
bool color[MAXN];
bool ans;
int n,l;
int init()
{
memset(node,0,sizeof(node));
memset(vis,0,sizeof(vis));
memset(color,0,sizeof(color));
ans=vis[0]=color[0]=1;
}
//这个dfs真的是挺简单;
void dfs(int u)
{
for(int v=0;v<n;v++)
{
if(node[u][v])//如果题目样例中给出了这条边,才说明他们联通;
{
if(!vis[v])//若没有判断过这个点,则给这个点颜色,并标记到过;
{
vis[v]=1;
color[v]=!color[u];
dfs(v);//从这个点再开始向下深搜,去搜和这个点相连的点;
}
else if(color[u]==color[v])//若已经到过了这个点,说明这个点已经有了颜色,那就需要判断和前一个点的颜色是不是一样;
{
ans=0;//ans其实是个标记,只要出现了两个相邻点颜色相同,则说明失败;
return;
}
}
}
}
int main()
{
int u,v;
while(scanf("%d",&n)&&n)
{
scanf("%d",&l);
init();
for(int i=0;i<l;i++)
{
scanf("%d%d",&u,&v);
node[u][v]=node[v][u]=1;//因为是无向图,所以两个方向都要赋上值;
}
dfs(0);
if(ans)
printf("BICOLORABLE.\n");
else
printf("NOT BICOLORABLE.\n");
}
return 0;
}
不要把简单的东西想复杂,没有思路,那就多看多学。