110901 Bicoloring


#include <vector>
#include <iostream>
#include <stdlib.h>

using namespace std;

class Graph
{
public:
	Graph(int vertexCnt)
	{
		m_vertexCnt = vertexCnt;

		int edges;
		cin >> edges;

		m_relations = new bool*[m_vertexCnt];
		for (int i = 0; i < m_vertexCnt; ++i)
			m_relations[i] = (bool*)calloc(m_vertexCnt, sizeof(bool));

		int a, b;
		for (int i = 0; i < edges; ++i)
		{
			cin >> a >> b;
			m_relations[a][b] = m_relations[b][a] = true;
		}
	}

	~Graph()
	{
		for (int i = 0; i < m_vertexCnt; ++i)
			free(m_relations[i]);
		delete[] m_relations;
	}

	enum Color_t
	{
		NO_COLOR = 0,
		RED,
		BLACK
	};

	bool IsBicolorable()
	{
		Color_t* vertexes = (Color_t*)calloc(m_vertexCnt, sizeof(Color_t));
		bool result = CheckIsBicolorable(vertexes);
		free(vertexes);
		return result;
	}

private:
	bool CheckIsBicolorable(Color_t* vertexes)
	{
		size_t processedCnt = 0;
		vector<int> vertexCol;
		vertexCol.push_back(0);
		vertexes[0] = RED;

		while(processedCnt < vertexCol.size())
		{
			int currentVertex = vertexCol[processedCnt];

			for (int i = 0; i < m_vertexCnt; ++i)
			{
				if (m_relations[currentVertex][i])
				{
					if (vertexes[i] == NO_COLOR)
					{
						vertexes[i] = GetOppositeColor(vertexes[currentVertex]);
						vertexCol.push_back(i);
					}
					else if (vertexes[i] == vertexes[currentVertex])
						return false;
				}
			}

			++processedCnt;
		}

		return true;
	}

	static Color_t GetOppositeColor(Color_t color)
	{
		if (color == RED)
			return BLACK;
		return RED;
	}

private:

	int m_vertexCnt;
	bool** m_relations;
};

static void Test()
{
	int vertexCnt;
	while(true)
	{
		cin >> vertexCnt;
		if (vertexCnt <= 0)
			return;

		Graph graph(vertexCnt);
		if (graph.IsBicolorable())
			cout << "BICOLORABLE." << endl;
		else
			cout << "NOT BICOLORABLE." << endl;
	}
}


int main(int argc, char* argv[])
{
	Test();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值