解析部グラフ(DFS染色)
グラフは二部グラフであるかどうかを決定する方法
正常染色テンプレート
テンプレートは以下のようにC ++コード
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int inf = 1000;
int V, E;
vector<int> G[inf];
int color[inf];
bool dfs(int node, int col)
{
color[node] = col; //染色
for (int i = 0; i < G[node].size; i++)
{
//如果相邻的顶点同色,就剪掉这一枝,返回false
if (color[G[node][i]] == col)
return false;
if (color[G[node][i]] == 0 && dfs(G[node][i],-col))
return false;
}
//如果都染了色返回true
return true;
}
void dfsTrave()
{
for (int i = 0; i < V; i++)
{
if (color[i] == 0)
{
if (!dfs(i, 1))
{
cout << "No" << endl;
return;
}
}
}
cout << "Yes" << endl;
}
int main()
{
cin >> V >> E;
int a, b;
for (int i = 0; i < E; i++)
{
cin >> a >> b;
G[a].push_back(b); //无向图存储两次
G[b].push_back(a); //如果是有向图只用存储一次即可
}
dfsTrave();
system("pause");
return 0;
}
あなたが私に置かれた任意の質問がある場合は、歓迎の首長が問題を指摘し、ああQQを追加することができます。
あなたがあなたの助けを感じる場合は、私に賞賛のポイントを与え、次回は私が^ _ ^それを書くのパワーを点灯しました