Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add graph_util #97

Merged
merged 18 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions cpp/graph_util.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#pragma once

/**
* @file graph_util.hpp
* @brief グラフに関する関数
*/

#include <stack>

#include "graph.hpp"

/**
* @brief 無向グラフについて、二部グラフなら0と1に彩色した結果をひとつ返し、二部グラフでないなら空のvectorを返す。
* 連結成分のうち、インデックスの小さいものを0にする。
* @return std::vector<int> 各頂点の彩色結果
*/
template <typename Cost = int>
std::vector<int> bipartite_coloring(const Graph<Cost>& graph) {
std::vector<int> color(graph.n, -1);
for (int i = 0; i < graph.n; i++) {
if (color[i] != -1) continue;
std::stack<int> stk;
stk.push(i);
color[i] = 0;
while (!stk.empty()) {
int u = stk.top();
stk.pop();
for (int v : graph[u]) {
if (color[v] == -1) {
color[v] = color[u] ^ 1;
stk.push(v);
} else {
if (color[u] == color[v]) return {};
}
}
}
}
return color;
}

/**
* @brief 無向グラフについて、二部グラフかどうかを判定する。
* @return bool 二部グラフならtrue、二部グラフでないならfalseを返す。
*/
template <typename Cost = int>
bool is_bipartite(const Graph<Cost>& graph) {
return !bipartite_coloring(graph).empty();
}
27 changes: 27 additions & 0 deletions test/atcoder-abc126-d.test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#define PROBLEM "https://atcoder.jp/contests/abc126/tasks/abc126_d"

Check failure on line 1 in test/atcoder-abc126-d.test.cpp

View workflow job for this annotation

GitHub Actions / verify

failed to verify
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

スペシャルジャッジの問題をverifyする手段が今のところないので、固定入出力の問題にするか #define IGNOREをつけてください。


#include "../cpp/graph_util.hpp"

int main() {
int N;
std::cin >> N;
Graph<int> graph(2 * N);
int tmp = N;
for (int i = 0; i < N - 1; i++) {
int u, v, w;
std::cin >> u >> v >> w;
u--;
v--;
if (w % 2) {
graph.add_edge(u, tmp);
graph.add_edge(v, tmp);
tmp++;
} else {
graph.add_edge(u, v);
}
}
std::vector<int> color = bipartite_coloring(graph);
for (int i = 0; i < N; i++) {
std::cout << color[i] << std::endl;
}
}
Loading