Skip to content

Commit

Permalink
add graph_util
Browse files Browse the repository at this point in the history
  • Loading branch information
shogo314 committed Nov 9, 2023
1 parent 3532649 commit 88abce5
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"files.associations": {
"algorithm": "cpp",
"iostream": "cpp"
}
}
45 changes: 45 additions & 0 deletions cpp/graph_util.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#pragma once

/**
* @file graph.hpp
* @brief 木の汎用テンプレート
*/

#include <stack>

#include "graph.hpp"

/**
* 無向グラフについて、二部グラフなら0と1に彩色した結果をひとつ返し、二部グラフでないなら空のvectorを返す。
**/
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;
}

/**
* 無向グラフについて、二部グラフならtrue、二部グラフでないならfalseを返す。
**/
template <typename Cost = int>
bool is_bipartite_graph(const Graph<Cost>& graph) {
return !bipartite_coloring(graph).empty();
}
22 changes: 22 additions & 0 deletions test/atcoder-code_festival_2017_qualb_c.test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#define PROBLEM "https://atcoder.jp/contests/code-festival-2017-qualb/tasks/code_festival_2017_qualb_c"

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

View workflow job for this annotation

GitHub Actions / verify

failed to verify

#include <array>

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

int main() {
int N, M;
std::cin >> N >> M;
Graph<int> graph(N);
graph.read(M, -1);
std::vector<int> color = bipartite_coloring(graph);

if (color.empty()) {
std::cout << (long long)N * (N - 1) / 2 - M << std::endl;
} else {
std::array<int, 2> cnt = {0, 0};
cnt[0] = count(color.begin(), color.end(), 0);
cnt[1] = count(color.begin(), color.end(), 1);
std::cout << (long long)cnt[0] * cnt[1] - M << std::endl;
}
}

0 comments on commit 88abce5

Please sign in to comment.