競技プログラミング用の C++ ライブラリ
#define PROBLEM "https://judge.yosupo.jp/problem/enumerate_triangles"
#include <iostream>
#include <vector>
#include "../../../src/graph/graph_util.hpp"
#include "../../../src/math/modint.hpp"
using mint = modint998244353;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, m;
std::cin >> n >> m;
std::vector<mint> x(n);
for (auto& v : x) std::cin >> v;
Graph<int> g(n);
g.read(m, 0);
mint ans = 0;
enumerate_triangles(g, [&](long long a, long long b, long long c) { ans += x[a] * x[b] * x[c]; });
std::cout << ans << '\n';
}#line 1 "test/yosupo/graph/enumerate-triangles.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/enumerate_triangles"
#include <iostream>
#include <vector>
#line 2 "src/graph/graph_util.hpp"
/**
* @file graph_util.hpp
* @brief グラフに関する関数
*/
#include <algorithm>
#include <cassert>
#include <functional>
#include <limits>
#include <optional>
#include <queue>
#include <stack>
#include <utility>
#line 17 "src/graph/graph_util.hpp"
#line 2 "src/data_structures/unionfind.hpp"
/**
* @file unionfind.hpp
* @brief UnionFind
*/
#line 12 "src/data_structures/unionfind.hpp"
namespace internal_unionfind {
/**
* @brief 各要素の代表元から、連結成分ごとの要素のリストを作る
* @param leader 要素 a の代表元を返す関数
*/
template <typename F>
std::vector<std::vector<long long>> groups(long long n, F leader) {
std::vector<long long> leader_buf(n), group_size(n);
for (long long i = 0; i < n; i++) {
leader_buf[i] = leader(i);
group_size[leader_buf[i]]++;
}
std::vector<std::vector<long long>> result(n);
for (long long i = 0; i < n; i++) {
result[i].reserve(group_size[i]);
}
for (long long i = 0; i < n; i++) {
result[leader_buf[i]].push_back(i);
}
result.erase(std::remove_if(result.begin(), result.end(), [&](const std::vector<long long>& v) { return v.empty(); }), result.end());
return result;
}
} // namespace internal_unionfind
/**
* @brief 無向グラフに対して「辺の追加」、「2頂点が連結かの判定」をする
*/
class UnionFind {
protected:
long long _n;
// 負ならサイズ、非負なら親 (メモリを抑えるため int で持つ)
std::vector<int> parent_or_size;
public:
/**
* @brief merge の戻り値
*
* if (uf.merge(a, b)) で新しく統合したかを判定でき、
* auto [r, merged] = uf.merge(a, b); で代表元も受け取れる
*/
struct MergeResult {
long long leader; //!< 統合後の代表元
bool merged; //!< 新しく統合したか (もともと同じ連結成分なら false)
explicit operator bool() const { return merged; }
};
UnionFind() : _n(0) {}
explicit UnionFind(long long n) : _n(n), parent_or_size(n, -1) {}
/**
* @brief 辺(a,b)を足す
* @return 統合後の代表元と、新しく統合したか
*/
MergeResult merge(long long a, long long b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
long long x = leader(a), y = leader(b);
if (x == y) return {x, false};
if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y);
parent_or_size[x] += parent_or_size[y];
parent_or_size[y] = static_cast<int>(x);
return {x, true};
}
/**
* @brief 頂点a,bが連結かどうか
*/
bool same(long long a, long long b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
return leader(a) == leader(b);
}
/**
* @brief 頂点aの属する連結成分の代表元
*/
long long leader(long long a) {
assert(0 <= a && a < _n);
if (parent_or_size[a] < 0) return a;
int x = static_cast<int>(a);
while (parent_or_size[x] >= 0) {
x = parent_or_size[x];
}
while (parent_or_size[a] >= 0) {
int t = parent_or_size[a];
parent_or_size[a] = x;
a = t;
}
return x;
}
/**
* @brief 頂点aの属する連結成分のサイズ
*/
long long size(long long a) {
assert(0 <= a && a < _n);
return -parent_or_size[leader(a)];
}
/**
* @brief グラフを連結成分に分け、その情報を返す
* @return 「一つの連結成分の頂点番号のリスト」のリスト
*/
std::vector<std::vector<long long>> groups() {
return internal_unionfind::groups(_n, [&](long long a) { return leader(a); });
}
};
#line 2 "src/graph/graph.hpp"
/**
* @file graph.hpp
* @brief グラフ
*/
#line 12 "src/graph/graph.hpp"
/**
* @brief グラフの汎用クラス
*
* @tparam Cost 辺のコストの型 省略したら long long (重みの和や未到達を表す max / 4 があふれにくいように)
*/
template <typename Cost = long long>
class Graph {
public:
/**
* @brief 有向辺の構造体
*
* operator long long()を定義しているので、整数型にキャストすると勝手にdstになる
* 例えば、
* for (auto& e : g[v]) をすると、vから出る辺が列挙されるが、
* for (long long dst : g[v]) とすると、vから出る辺の行き先が列挙される
*/
struct Edge {
long long src = -1; //!< 始点
long long dst = -1; //!< 終点
Cost cost = {}; //!< コスト
long long id = -1; //!< 辺の番号(追加された順、無向辺の場合はidが同じで方向が逆のものが2つ存在する)
Edge() = default;
Edge(long long src, long long dst, Cost cost = 1, long long id = -1) : src(src), dst(dst), cost(cost), id(id) {}
operator long long() const { return dst; }
};
private:
long long n; //!< 頂点数
long long m; //!< 辺数
std::vector<std::vector<Edge>> g; //!< グラフの隣接リスト表現
public:
/**
* @brief デフォルトコンストラクタ
*/
Graph() : n(0), m(0), g(0) {}
/**
* @brief コンストラクタ
* @param n 頂点数
*/
explicit Graph(long long n) : n(n), m(0), g(n) {}
/**
* @brief 頂点数
*/
long long size() const { return n; }
/**
* @brief 辺数 (無向辺は 1 本と数える)
*/
long long edge_count() const { return m; }
/**
* @brief 無向辺を追加する
* @param u 始点
* @param v 終点
* @param w コスト 省略したら1
*/
void add_edge(long long u, long long v, Cost w = 1) {
assert(0 <= u && u < n && 0 <= v && v < n);
g[u].push_back({u, v, w, m});
g[v].push_back({v, u, w, m++});
}
/**
* @brief 有向辺を追加する
* @param u 始点
* @param v 終点
* @param w コスト 省略したら1
*/
void add_directed_edge(long long u, long long v, Cost w = 1) {
assert(0 <= u && u < n && 0 <= v && v < n);
g[u].push_back({u, v, w, m++});
}
/**
* @brief 辺の情報を標準入力から受け取って追加する
* @param m 辺の数
* @param padding 頂点番号を入力からいくつずらすか 省略したら-1
* @param weighted 辺の重みが入力されるか 省略したらfalseとなり、重み1で辺が追加される
* @param directed 有向グラフかどうか 省略したらfalse
*/
void read(long long m, long long padding = -1, bool weighted = false, bool directed = false) {
for (long long i = 0; i < m; i++) {
long long u, v;
std::cin >> u >> v;
u += padding, v += padding;
Cost c(1);
if (weighted)
std::cin >> c;
if (directed)
add_directed_edge(u, v, c);
else
add_edge(u, v, c);
}
}
/**
* @brief ある頂点から出る辺を列挙する
* @param v 頂点番号
* @return const std::vector<Edge>& vから出る辺のリスト
*/
const std::vector<Edge>& operator[](long long v) const {
assert(0 <= v && v < n);
return g[v];
}
/**
* @brief 辺のリスト
* @return std::vector<Edge> 辺のリスト(idの昇順)
*
* 無向辺は代表して1つだけ格納される。その src と dst の向きは規定しない
* 有向辺は追加したときの向きのまま格納される
*/
std::vector<Edge> edges() const {
std::vector<Edge> res(m);
for (long long i = 0; i < n; i++) {
for (auto& e : g[i]) {
res[e.id] = e;
}
}
return res;
}
};
/**
* @brief 経路 (路・閉路)。長さ cost、たどる頂点の列 vertices、たどる辺の列 edges
*
* edges[k] は vertices[k] から vertices[k + 1] へ向かう (edges[k].src == vertices[k]、edges[k].dst == vertices[k + 1])
* vertices は edges より 1 つ多い。辺がなくても始点 1 つが入る。閉路なら vertices.front() == vertices.back()
* auto [cost, vertices, edges] = *shortest_path(g, s, t); のように受け取れる
*/
template <typename Cost>
struct Path {
Cost cost; //!< 長さ (辺のコストの和)
std::vector<long long> vertices; //!< たどる頂点 (始点から順に)
std::vector<typename Graph<Cost>::Edge> edges; //!< たどる辺 (始点側から順に)
};
namespace internal_graph {
/**
* @brief 始点 s と、s からたどる順に並べた辺 edges から Path を作る。cost は辺のコストの和
*/
template <typename Cost>
Path<Cost> make_path(long long s, std::vector<typename Graph<Cost>::Edge> edges) {
Path<Cost> res{Cost{}, {s}, std::move(edges)};
for (const auto& e : res.edges) {
assert(e.src == res.vertices.back());
res.cost += e.cost;
res.vertices.push_back(e.dst);
}
return res;
}
} // namespace internal_graph
#line 20 "src/graph/graph_util.hpp"
/**
* @brief 無向グラフについて、二部グラフなら0と1に彩色した結果をひとつ返し、二部グラフでないならstd::nulloptを返す。
* 連結成分のうち、インデックスの最も小さいものを0にする。
* @return std::optional<std::vector<int>> 各頂点の彩色結果
*/
template <typename Cost = long long>
std::optional<std::vector<int>> bipartite_coloring(const Graph<Cost>& graph) {
std::vector<int> color(graph.size(), -1);
for (long long i = 0; i < graph.size(); i++) {
if (color[i] != -1) continue;
std::stack<long long> stk;
stk.push(i);
color[i] = 0;
while (!stk.empty()) {
long long u = stk.top();
stk.pop();
for (long long v : graph[u]) {
if (color[v] == -1) {
color[v] = color[u] ^ 1;
stk.push(v);
} else {
if (color[u] == color[v]) return std::nullopt;
}
}
}
}
return color;
}
/**
* @brief 無向グラフについて、二部グラフかどうかを判定する。
* @return bool 二部グラフならtrue、二部グラフでないならfalseを返す。
*/
template <typename Cost = long long>
bool is_bipartite(const Graph<Cost>& graph) {
return bipartite_coloring(graph).has_value();
}
/**
* @brief 無向グラフについて、連結成分分解する。
* @return std::vector<std::vector<long long>> 「同じ連結成分となる頂点のリスト」のリスト
*/
template <typename Cost = long long>
std::vector<std::vector<long long>> connected_components(const Graph<Cost>& graph) {
std::vector<std::vector<long long>> groups;
std::vector<bool> visited(graph.size());
for (long long i = 0; i < graph.size(); i++) {
if (visited[i]) continue;
std::stack<long long> stk;
stk.push(i);
visited[i] = true;
groups.push_back({i});
while (!stk.empty()) {
long long u = stk.top();
stk.pop();
for (long long v : graph[u]) {
if (visited[v]) continue;
visited[v] = true;
stk.push(v);
groups.back().push_back(v);
}
}
}
return groups;
}
/**
* @brief 無向グラフの補グラフ (辺のない 2 頂点の間に辺を張ったグラフ) を連結成分分解する O(n + m)
* まだどの成分にも入っていない頂点の列を持ち、取り出した頂点と隣り合わないものを同じ成分に移す
*/
template <typename Cost = long long>
std::vector<std::vector<long long>> complement_connected_components(const Graph<Cost>& graph) {
const long long n = graph.size();
std::vector<long long> rest(n);
for (long long i = 0; i < n; i++) rest[i] = i;
std::vector<bool> adj(n, false);
std::vector<std::vector<long long>> groups;
while (!rest.empty()) {
groups.push_back({rest.back()});
rest.pop_back();
// groups.back() の i 番目の頂点を取り出し、rest のうち隣り合わないものを成分に移す
for (long long i = 0; i < static_cast<long long>(groups.back().size()); i++) {
const long long u = groups.back()[i];
for (long long v : graph[u]) adj[v] = true;
std::vector<long long> keep;
for (long long v : rest) {
if (adj[v]) {
keep.push_back(v);
} else {
groups.back().push_back(v);
}
}
rest.swap(keep);
for (long long v : graph[u]) adj[v] = false;
}
}
return groups;
}
/**
* @brief 無向グラフについて、連結グラフかどうかを判定する。
* @return bool 連結グラフならtrue、連結グラフでないならfalseを返す。
*/
template <typename Cost = long long>
bool is_connected(const Graph<Cost>& graph) {
return connected_components(graph).size() == 1;
}
/**
* @brief 無向グラフについて、木かどうかを判定する。
* @return bool 木ならtrue、木でないならfalseを返す。
*/
template <typename Cost = long long>
bool is_tree(const Graph<Cost>& graph) {
return graph.edge_count() == graph.size() - 1 && is_connected(graph);
}
/**
* @brief 有向グラフをトポロジカルソートする
* @return std::optional<std::vector<long long>> トポロジカル順に並べた頂点のリスト。DAG でなければ std::nullopt
*/
template <typename Cost = long long>
std::optional<std::vector<long long>> topological_sort(const Graph<Cost>& graph) {
std::vector<int> indeg(graph.size());
std::vector<long long> sorted;
std::queue<long long> q;
for (long long i = 0; i < graph.size(); i++) {
for (long long dst : graph[i]) indeg[dst]++;
}
for (long long i = 0; i < graph.size(); i++) {
if (!indeg[i]) q.push(i);
}
while (!q.empty()) {
long long cur = q.front();
q.pop();
for (long long dst : graph[cur]) {
if (!--indeg[dst]) q.push(dst);
}
sorted.push_back(cur);
}
if (static_cast<long long>(sorted.size()) < graph.size()) return std::nullopt;
return sorted;
}
/**
* @brief 有向グラフについて、サイクルをもつかどうかを判定する。
* 無向グラフには使えない (辺が 1 本でもあれば true になる)。無向グラフは has_cycle_undirected
* @return bool サイクルをもつならtrue、非巡回ならfalseを返す。
*/
template <typename Cost = long long>
bool has_cycle_directed(const Graph<Cost>& graph) {
return !topological_sort(graph).has_value();
}
/**
* @brief 無向グラフについて、閉路をもつか (森でないか) を判定する
*
* 辺の数が n - (連結成分の数) より多いかで判定する。自己ループと多重辺も閉路とみなす。O(n + m)
*/
template <typename Cost = long long>
bool has_cycle_undirected(const Graph<Cost>& graph) {
return graph.edge_count() > graph.size() - static_cast<long long>(connected_components(graph).size());
}
/**
* @brief 有向グラフの閉路を 1 つ求める
*
* DFS を再帰を使わずに行う。O(n + m)
* @return std::optional<Path<Cost>> 閉路 (重みの和、たどる頂点、たどる辺)。vertices.front() == vertices.back()。閉路がなければ std::nullopt
* 自己ループは辺 1 本の閉路になる
*/
template <typename Cost = long long>
std::optional<Path<Cost>> find_cycle_directed(const Graph<Cost>& graph) {
using Edge = typename Graph<Cost>::Edge;
// state: 0 は未訪問、1 は DFS のスタック上、2 は探索済み
std::vector<int> state(graph.size(), 0), iter(graph.size(), 0);
std::vector<Edge> in(graph.size()); // DFS 木で v に入る辺
for (long long root = 0; root < graph.size(); root++) {
if (state[root]) continue;
std::vector<long long> st = {root};
state[root] = 1;
while (!st.empty()) {
long long v = st.back();
if (iter[v] == static_cast<int>(graph[v].size())) {
state[v] = 2;
st.pop_back();
continue;
}
const Edge& e = graph[v][iter[v]++];
long long u = e.dst;
if (state[u] == 0) {
state[u] = 1;
in[u] = e;
st.push_back(u);
} else if (state[u] == 1) {
// u はスタック上にあるので、u から v への木の辺と e で閉路になる
std::vector<Edge> res = {e};
for (long long w = v; w != u; w = in[w].src) res.push_back(in[w]);
std::reverse(res.begin(), res.end());
return internal_graph::make_path<Cost>(u, std::move(res));
}
}
}
return std::nullopt;
}
/**
* @brief 無向グラフの閉路を 1 つ求める
*
* DFS を再帰を使わずに行う。O(n + m)
* @return std::optional<Path<Cost>> 閉路 (重みの和、たどる頂点、たどる辺)。vertices.front() == vertices.back()。閉路がなければ std::nullopt
* 自己ループは辺 1 本、多重辺は辺 2 本の閉路になる (同じ辺を戻ることはない)
*/
template <typename Cost = long long>
std::optional<Path<Cost>> find_cycle_undirected(const Graph<Cost>& graph) {
using Edge = typename Graph<Cost>::Edge;
std::vector<int> state(graph.size(), 0), iter(graph.size(), 0);
std::vector<Edge> in(graph.size());
for (long long root = 0; root < graph.size(); root++) {
if (state[root]) continue;
std::vector<long long> st = {root};
state[root] = 1;
while (!st.empty()) {
long long v = st.back();
if (iter[v] == static_cast<int>(graph[v].size())) {
state[v] = 2;
st.pop_back();
continue;
}
const Edge& e = graph[v][iter[v]++];
// 親へ戻る辺は、頂点ではなく辺の番号で区別する (多重辺を閉路として見つけるため)
if (e.id == in[v].id) continue; // 根では in[v].id == -1
long long u = e.dst;
if (state[u] == 0) {
state[u] = 1;
in[u] = e;
st.push_back(u);
} else if (state[u] == 1) {
// u は v の祖先 (か v 自身) なので、u から v への木の辺と e で閉路になる
std::vector<Edge> res = {e};
for (long long w = v; w != u; w = in[w].src) res.push_back(in[w]);
std::reverse(res.begin(), res.end());
return internal_graph::make_path<Cost>(u, std::move(res));
}
// state[u] == 2 にはならない (なるなら、u の側でこの辺により閉路が見つかっている)
}
}
return std::nullopt;
}
/**
* @brief 有向グラフを強連結成分分解する
*
* Tarjan のアルゴリズムを再帰を使わずに行う。O(n + m)
*
* @return std::vector<std::vector<long long>> 強連結成分ごとの頂点のリスト。
* 成分はトポロジカル順に並ぶ (成分 A から成分 B へ辺があれば A が B より前)
*/
template <typename Cost = long long>
std::vector<std::vector<long long>> strongly_connected_components(const Graph<Cost>& graph) {
const long long n = graph.size();
std::vector<int> ord(n, -1), low(n), comp(n, -1), iter(n, 0);
std::vector<long long> visiting; // 成分がまだ決まっていない訪問済みの頂点
std::vector<long long> call; // DFS の呼び出しスタック
int now = 0, k = 0;
for (long long s = 0; s < n; s++) {
if (ord[s] != -1) continue;
ord[s] = low[s] = now++;
visiting.push_back(s);
call.push_back(s);
while (!call.empty()) {
long long v = call.back();
if (iter[v] < static_cast<int>(graph[v].size())) {
long long to = graph[v][iter[v]++].dst;
if (ord[to] == -1) {
ord[to] = low[to] = now++;
visiting.push_back(to);
call.push_back(to);
} else if (comp[to] == -1) {
low[v] = std::min(low[v], ord[to]);
}
continue;
}
call.pop_back();
if (!call.empty()) low[call.back()] = std::min(low[call.back()], low[v]);
if (low[v] == ord[v]) {
while (true) {
long long u = visiting.back();
visiting.pop_back();
comp[u] = k;
if (u == v) break;
}
k++;
}
}
}
// Tarjan のアルゴリズムは成分をトポロジカル順の逆に見つけるので、逆順に並べる
std::vector<std::vector<long long>> groups(k);
for (long long v = 0; v < n; v++) groups[k - 1 - comp[v]].push_back(v);
return groups;
}
/**
* @brief 最小全域木の結果
*/
template <typename Cost>
struct MinimumSpanningTree {
Cost cost; //!< 使った辺のコストの総和
std::vector<typename Graph<Cost>::Edge> edges; //!< 使った辺 (コストの昇順、同じコストなら辺の番号順)
};
/**
* @brief 無向グラフの最小全域木 (Kruskal 法) O(m log m)
*
* 連結でなければ、各連結成分の最小全域木を合わせたもの (最小全域森) を返す
* 連結かどうかは edges.size() == n - 1 で判定できる
*/
template <typename Cost = long long>
MinimumSpanningTree<Cost> minimum_spanning_tree(const Graph<Cost>& graph) {
auto es = graph.edges();
std::stable_sort(es.begin(), es.end(), [](const auto& a, const auto& b) { return a.cost < b.cost; });
UnionFind uf(graph.size());
MinimumSpanningTree<Cost> res{Cost{}, {}};
for (const auto& e : es) {
if (uf.merge(e.src, e.dst)) {
res.cost += e.cost;
res.edges.push_back(e);
}
}
return res;
}
/**
* @brief 無向グラフの彩色数 (隣り合う頂点が同じ色にならないように塗るときの色の最小数。頂点数 20 程度まで) O(3^n)
* 独立集合の表を O(2^n) で作り、dp[S] = min (dp[S \ T] + 1) を、T を「S の最小の頂点 v を含み、v と隣り合わない S の頂点からなる独立集合」に限って求める
* 枝刈りで速くなるのは定数倍だけで、2 頂点ずつ辺で結んだグラフなどでは内側のループが 3^n / 2 回近くまわる
* 頂点がなければ 0。自己ループがあれば塗れないので -1
*/
template <typename Cost = long long>
long long chromatic_number(const Graph<Cost>& graph) {
const int n = graph.size();
if (n == 0) return 0;
assert(n <= 30);
std::vector<int> adj(n, 0);
for (int v = 0; v < n; v++) {
for (const auto& e : graph[v]) {
if (e.dst == v) return -1;
adj[v] |= 1 << e.dst;
}
}
// indep[S]: S が独立集合か (最小の頂点を除いた集合が独立で、最小の頂点がそれと隣り合わない)
std::vector<bool> indep(1 << n, false);
indep[0] = true;
for (int S = 1; S < (1 << n); S++) {
const int v = __builtin_ctz(S), rest = S & (S - 1);
indep[S] = indep[rest] && !(adj[v] & rest);
}
std::vector<int> dp(1 << n, n + 1);
dp[0] = 0;
for (int S = 1; S < (1 << n); S++) {
if (indep[S]) {
dp[S] = 1;
continue;
}
const int v = __builtin_ctz(S), low = 1 << v, cand = S & ~adj[v] & ~low;
for (int U = cand;; U = (U - 1) & cand) {
const int T = U | low;
if (indep[T] && dp[S ^ T] + 1 < dp[S]) dp[S] = dp[S ^ T] + 1;
if (U == 0) break;
}
}
return dp[(1 << n) - 1];
}
/**
* @brief 無向グラフの最大独立集合 (どの 2 頂点も隣り合わない頂点集合で、要素数が最大のもの) を 1 つ求め、頂点を昇順に返す (頂点数 64 以下)
* 次数 1 以下の頂点は選んでよいので選び、そうでなければ次数最大の頂点を選ぶか選ばないかで分岐する。O(1.39^n) 程度 (n = 40 で十分速い)
* @note 自己ループのある頂点は選ばない
*/
template <typename Cost = long long>
std::vector<long long> maximum_independent_set(const Graph<Cost>& graph) {
const int n = graph.size();
assert(n <= 64);
using u64 = unsigned long long;
std::vector<u64> adj(n, 0);
u64 all = n == 64 ? ~0ULL : (1ULL << n) - 1;
for (int u = 0; u < n; u++) {
for (const auto& e : graph[u]) {
if (e.dst == u) {
all &= ~(1ULL << u);
} else {
adj[u] |= 1ULL << e.dst;
}
}
}
u64 best = 0;
// rest: まだ決めていない頂点、cur: 選んだ頂点
auto rec = [&](auto self, u64 rest, u64 cur) -> void {
if (__builtin_popcountll(cur) + __builtin_popcountll(rest) <= __builtin_popcountll(best)) return;
if (rest == 0) {
best = cur;
return;
}
int v = -1, deg = -1;
for (u64 r = rest; r; r &= r - 1) {
const int u = __builtin_ctzll(r), d = __builtin_popcountll(adj[u] & rest);
if (d <= 1) {
// 次数 1 以下なら選んでも損をしない
self(self, rest & ~adj[u] & ~(1ULL << u), cur | 1ULL << u);
return;
}
if (d > deg) v = u, deg = d;
}
self(self, rest & ~adj[v] & ~(1ULL << v), cur | 1ULL << v);
self(self, rest & ~(1ULL << v), cur);
};
rec(rec, all, 0);
std::vector<long long> res;
for (int v = 0; v < n; v++)
if (best >> v & 1) res.push_back(v);
return res;
}
/**
* @brief 単純な無向グラフの三角形 (互いに隣り合う 3 頂点) をすべて列挙し、それぞれについて f(a, b, c) (a < b < c) を呼ぶ O(m sqrt(m))
* 辺を次数の小さい方から大きい方へ向けると、各頂点から出る辺は O(sqrt(m)) 本になる
* @note 自己ループと多重辺はないこと
*/
template <typename Cost, typename F>
void enumerate_triangles(const Graph<Cost>& graph, F f) {
const long long n = graph.size();
auto less = [&](long long u, long long v) {
return graph[u].size() != graph[v].size() ? graph[u].size() < graph[v].size() : u < v;
};
std::vector<std::vector<long long>> out(n);
for (long long u = 0; u < n; u++) {
for (const auto& e : graph[u])
if (less(u, e.dst)) out[u].push_back(e.dst);
}
std::vector<bool> mark(n, false);
for (long long u = 0; u < n; u++) {
for (long long v : out[u]) mark[v] = true;
for (long long v : out[u]) {
for (long long w : out[v]) {
if (!mark[w]) continue;
long long t[3] = {u, v, w};
std::sort(t, t + 3);
f(t[0], t[1], t[2]);
}
}
for (long long v : out[u]) mark[v] = false;
}
}
namespace internal_graph_util {
/**
* @brief minimum_steiner_tree の DP
* dp[k][i]: 頂点 k を含み、X の部分集合 i をすべて含む部分木の重みの最小値
* from[k][i]: 復元用。type が -1 なら X の頂点そのもの、0 なら i を x と i ^ x に分けた、1 なら頂点 x から辺 id を通って来た
*/
struct SteinerFrom {
int type = -1;
long long x = -1, id = -1;
};
template <typename Cost>
struct SteinerDP {
std::vector<std::vector<Cost>> dp;
std::vector<std::vector<SteinerFrom>> from;
};
template <typename Cost, typename T>
SteinerDP<Cost> steiner_dp(const Graph<Cost>& graph, const std::vector<T>& X, Cost inf, bool restore) {
for (const auto& x : X) assert(0 <= x && x < graph.size());
const int full = 1 << X.size();
SteinerDP<Cost> res;
auto& dp = res.dp;
dp.assign(graph.size(), std::vector<Cost>(full, inf));
if (restore) res.from.assign(graph.size(), std::vector<SteinerFrom>(full));
for (int p = 0; p < static_cast<int>(X.size()); p++) dp[X[p]][1 << p] = {};
for (int i = 0; i < full; i++) {
for (int j = i; j > 0; j = (j - 1) & i) {
for (long long k = 0; k < graph.size(); k++) {
if (dp[k][j] != inf && dp[k][i ^ j] != inf) {
if (dp[k][i] == inf || dp[k][i] > dp[k][j] + dp[k][i ^ j]) {
dp[k][i] = dp[k][j] + dp[k][i ^ j];
if (restore) res.from[k][i] = {0, j, -1};
}
}
}
}
std::priority_queue<std::pair<Cost, long long>, std::vector<std::pair<Cost, long long>>, std::greater<std::pair<Cost, long long>>> que;
for (long long k = 0; k < graph.size(); k++)
if (dp[k][i] != inf) que.emplace(dp[k][i], k);
while (que.size()) {
auto [d, u] = que.top();
que.pop();
if (d > dp[u][i]) continue;
for (auto e : graph[u]) {
if (dp[e.dst][i] == inf || dp[e.dst][i] > d + e.cost) {
dp[e.dst][i] = d + e.cost;
if (restore) res.from[e.dst][i] = {1, u, e.id};
que.emplace(d + e.cost, e.dst);
}
}
}
}
return res;
}
} // namespace internal_graph_util
namespace internal_graph_util {
/**
* @brief steiner_dp の結果から、X をすべて含む部分木の重みが最小になる根を返す。X を連結にできなければ -1
*/
template <typename Cost>
long long steiner_root(const std::vector<std::vector<Cost>>& dp, Cost inf) {
long long root = -1;
for (long long k = 0; k < static_cast<long long>(dp.size()); k++) {
if (dp[k].back() != inf && (root == -1 || dp[root].back() > dp[k].back())) root = k;
}
return root;
}
} // namespace internal_graph_util
/**
* @brief 頂点集合 X をすべて含む部分木の辺の重みの総和の最小値 O(3^k n + 2^k m log m) (k = |X|)
* @param inf 内部の DP で「まだ作れない」を表す値。答えになりうるどの値よりも大きくすること
* @return std::optional<Cost> 最小値。X を連結にできなければ std::nullopt
* @note 無向グラフ。X が空なら 0
*/
template <typename Cost, typename T>
std::optional<Cost> minimum_steiner_tree(const Graph<Cost>& graph, const std::vector<T>& X, Cost inf = std::numeric_limits<Cost>::max() / 4) {
if (X.empty()) return Cost{};
const auto dp = internal_graph_util::steiner_dp(graph, X, inf, false).dp;
const long long root = internal_graph_util::steiner_root(dp, inf);
if (root == -1) return std::nullopt;
return dp[root].back();
}
/**
* @brief minimum_steiner_tree_restore の結果
*
* auto [cost, edges] = *minimum_steiner_tree_restore(g, X); のように受け取れる
*/
template <typename Cost>
struct MinimumSteinerTree {
Cost cost; //!< 使った辺の重みの総和
std::vector<typename Graph<Cost>::Edge> edges; //!< 使った辺 (辺の番号順)
};
/**
* @brief 頂点集合 X をすべて含む重み最小の部分木を 1 つ求め、重みの総和と使った辺を返す
* 計算量は minimum_steiner_tree と同じ
* @param inf minimum_steiner_tree と同じ
* @return std::optional<MinimumSteinerTree<Cost>> 重みの総和と、使った辺 (辺の番号順)。X を連結にできなければ std::nullopt
* @note 無向グラフ。X が空なら重み 0 で辺は空
*/
template <typename Cost, typename T>
std::optional<MinimumSteinerTree<Cost>> minimum_steiner_tree_restore(const Graph<Cost>& graph, const std::vector<T>& X, Cost inf = std::numeric_limits<Cost>::max() / 4) {
if (X.empty()) return MinimumSteinerTree<Cost>{Cost{}, {}};
const auto [dp, from] = internal_graph_util::steiner_dp(graph, X, inf, true);
const long long root = internal_graph_util::steiner_root(dp, inf);
if (root == -1) return std::nullopt;
// 辺の重みが 0 だと同じ辺を 2 回使うことがあるので、最後に重複を除く
std::vector<long long> res;
std::vector<std::pair<long long, int>> stk = {{root, static_cast<int>(dp[root].size()) - 1}};
while (!stk.empty()) {
auto [k, i] = stk.back();
stk.pop_back();
const auto& f = from[k][i];
if (f.type == 0) {
stk.emplace_back(k, static_cast<int>(f.x));
stk.emplace_back(k, i ^ static_cast<int>(f.x));
} else if (f.type == 1) {
res.push_back(f.id);
stk.emplace_back(f.x, i);
}
}
std::sort(res.begin(), res.end());
res.erase(std::unique(res.begin(), res.end()), res.end());
const auto all = graph.edges();
MinimumSteinerTree<Cost> tree{dp[root].back(), {}};
for (long long id : res) tree.edges.push_back(all[id]);
return tree;
}
#line 2 "src/math/modint.hpp"
/**
* @file modint.hpp
* @brief 四則演算において自動で mod を取るクラス
*/
#line 9 "src/math/modint.hpp"
#include <cstdint>
#line 12 "src/math/modint.hpp"
#include <type_traits>
#line 14 "src/math/modint.hpp"
#line 2 "src/utility/traits.hpp"
/**
* @file traits.hpp
* @brief 型特性
*/
#include <cstddef>
#line 10 "src/utility/traits.hpp"
#include <iterator>
#include <set>
#line 14 "src/utility/traits.hpp"
#if __cplusplus >= 202002L
#include <concepts>
#include <ranges>
#endif
namespace internal_traits {
using std::begin, std::end;
#if __cplusplus >= 202002L
template <class T>
struct is_range_impl : std::bool_constant < requires(T& t) {
begin(t);
end(t);
}>{};
#else
template <class T, class = void>
struct is_range_impl : std::false_type {};
template <class T>
struct is_range_impl<T, std::void_t<decltype(begin(std::declval<T&>()), end(std::declval<T&>()))>> : std::true_type {};
#endif
// サイズ付き範囲から要素を直接構築するコンストラクタで共有する。
#if __cplusplus >= 202002L
template <class R, class S>
concept sized_constructible_range = std::ranges::input_range<R> && std::ranges::sized_range<R> &&
std::is_constructible_v<S, std::ranges::range_reference_t<R>>;
template <class R>
auto range_size(R& r) {
return std::ranges::size(r);
}
template <class R>
auto range_begin(R& r) {
return std::ranges::begin(r);
}
template <class R>
using range_value_t = std::ranges::range_value_t<R>;
#else
using std::size;
template <class R>
auto range_size(R& r) -> decltype(size(r)) {
return size(r);
}
template <class R>
auto range_begin(R& r) -> decltype(begin(r)) {
return begin(r);
}
template <class R>
using range_value_t = typename std::iterator_traits<decltype(range_begin(std::declval<R&>()))>::value_type;
template <class R, class S, class = void>
struct is_sized_constructible_range : std::false_type {};
template <class R, class S>
struct is_sized_constructible_range<R, S, std::void_t<decltype(range_size(std::declval<R&>())), decltype(++std::declval<decltype(begin(std::declval<R&>()))&>()), decltype(begin(std::declval<R&>()) != end(std::declval<R&>())), decltype(*begin(std::declval<R&>()))>>
: std::is_constructible<S, decltype(*begin(std::declval<R&>()))> {};
#endif
} // namespace internal_traits
template <class T>
struct is_range : internal_traits::is_range_impl<T>::type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;
#if __cplusplus >= 202002L
#define HAS_METHOD(func_name) \
namespace internal_traits { \
template <class T> \
concept has_##func_name##_impl = requires { std::declval<T>().func_name(); }; \
} \
template <class T> \
struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T>> {}; \
template <class T> \
inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;
#define HAS_METHOD_ARG(func_name) \
namespace internal_traits { \
template <class T, class U> \
concept has_##func_name##_impl = requires { std::declval<T>().func_name(std::declval<U>()); }; \
} \
template <class T, class U> \
struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T, U>> {}; \
template <class T, class U> \
inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#else
#define HAS_METHOD(func_name) \
namespace internal_traits { \
template <class T, class = void> \
struct has_##func_name##_impl : std::false_type {}; \
template <class T> \
struct has_##func_name##_impl<T, std::void_t<decltype(std::declval<T>().func_name())>> \
: std::true_type {}; \
} \
template <class T> \
struct has_##func_name : internal_traits::has_##func_name##_impl<T>::type {}; \
template <class T> \
inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;
#define HAS_METHOD_ARG(func_name) \
namespace internal_traits { \
template <class T, typename U, class = void> \
struct has_##func_name##_impl : std::false_type {}; \
template <class T, typename U> \
struct has_##func_name##_impl<T, U, std::void_t<decltype(std::declval<T>().func_name(std::declval<U>()))>> \
: std::true_type {}; \
} \
template <class T, typename U> \
struct has_##func_name : internal_traits::has_##func_name##_impl<T, U>::type {}; \
template <class T, typename U> \
inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#endif
HAS_METHOD(repr)
HAS_METHOD(type_str)
HAS_METHOD(initializer_str)
HAS_METHOD(max)
HAS_METHOD(min)
HAS_METHOD(reversed)
HAS_METHOD(sorted)
HAS_METHOD(sum)
HAS_METHOD(product)
HAS_METHOD(product_xor)
HAS_METHOD_ARG(count)
HAS_METHOD_ARG(find)
HAS_METHOD_ARG(lower_bound)
HAS_METHOD_ARG(upper_bound)
#define ENABLE_IF_T_IMPL(expr) std::enable_if_t<expr, std::nullptr_t> = nullptr
#define ENABLE_IF_T(...) ENABLE_IF_T_IMPL((__VA_ARGS__))
namespace internal_traits {
// 射影 (proj) の既定値
#if __cplusplus >= 202002L
using identity = std::identity;
#else
struct identity {
using is_transparent = void;
template <class T>
constexpr T&& operator()(T&& x) const noexcept {
return std::forward<T>(x);
}
};
#endif
} // namespace internal_traits
template <class C>
using mem_value_type = typename C::value_type;
template <class C>
using mem_difference_type = typename C::difference_type;
namespace internal_traits {
template <class T, class = void>
struct is_sorted_container_impl : std::false_type {};
template <class T>
struct is_sorted_container_impl<std::set<T>> : std::true_type {};
template <class T>
struct is_sorted_container_impl<std::multiset<T>> : std::true_type {};
} // namespace internal_traits
template <class T>
struct is_sorted_container : internal_traits::is_sorted_container_impl<T>::type {};
template <class T>
inline constexpr bool is_sorted_container_v = is_sorted_container<T>::value;
#line 16 "src/math/modint.hpp"
namespace internal_modint {
// clang-format off
static constexpr std::uint16_t prime32_bases[] {
15591, 2018, 166, 7429, 8064, 16045, 10503, 4399, 1949, 1295, 2776, 3620, 560, 3128, 5212, 2657,
2300, 2021, 4652, 1471, 9336, 4018, 2398, 20462, 10277, 8028, 2213, 6219, 620, 3763, 4852, 5012,
3185, 1333, 6227, 5298, 1074, 2391, 5113, 7061, 803, 1269, 3875, 422, 751, 580, 4729, 10239,
746, 2951, 556, 2206, 3778, 481, 1522, 3476, 481, 2487, 3266, 5633, 488, 3373, 6441, 3344,
17, 15105, 1490, 4154, 2036, 1882, 1813, 467, 3307, 14042, 6371, 658, 1005, 903, 737, 1887,
7447, 1888, 2848, 1784, 7559, 3400, 951, 13969, 4304, 177, 41, 19875, 3110, 13221, 8726, 571,
7043, 6943, 1199, 352, 6435, 165, 1169, 3315, 978, 233, 3003, 2562, 2994, 10587, 10030, 2377,
1902, 5354, 4447, 1555, 263, 27027, 2283, 305, 669, 1912, 601, 6186, 429, 1930, 14873, 1784,
1661, 524, 3577, 236, 2360, 6146, 2850, 55637, 1753, 4178, 8466, 222, 2579, 2743, 2031, 2226,
2276, 374, 2132, 813, 23788, 1610, 4422, 5159, 1725, 3597, 3366, 14336, 579, 165, 1375, 10018,
12616, 9816, 1371, 536, 1867, 10864, 857, 2206, 5788, 434, 8085, 17618, 727, 3639, 1595, 4944,
2129, 2029, 8195, 8344, 6232, 9183, 8126, 1870, 3296, 7455, 8947, 25017, 541, 19115, 368, 566,
5674, 411, 522, 1027, 8215, 2050, 6544, 10049, 614, 774, 2333, 3007, 35201, 4706, 1152, 1785,
1028, 1540, 3743, 493, 4474, 2521, 26845, 8354, 864, 18915, 5465, 2447, 42, 4511, 1660, 166,
1249, 6259, 2553, 304, 272, 7286, 73, 6554, 899, 2816, 5197, 13330, 7054, 2818, 3199, 811,
922, 350, 7514, 4452, 3449, 2663, 4708, 418, 1621, 1171, 3471, 88, 11345, 412, 1559, 194,
};
// clang-format on
static constexpr bool is_SPRP(std::uint32_t n, std::uint32_t a) noexcept {
std::uint32_t d = n - 1;
std::uint32_t s = 0;
while ((d & 1) == 0) {
++s;
d >>= 1;
}
std::uint64_t cur = 1;
std::uint64_t pw = d;
while (pw) {
if (pw & 1) cur = (cur * a) % n;
a = (static_cast<std::uint64_t>(a) * a) % n;
pw >>= 1;
}
if (cur == 1) return true;
for (std::uint32_t r = 0; r < s; ++r) {
if (cur == n - 1) return true;
cur = (cur * cur) % n;
}
return false;
}
// 32ビット符号なし整数の素数判定
// 参考: M. Forisek and J. Jancina, “Fast Primality Testing for Integers That Fit into a Machine Word,” presented at the Conference on Current Trends in Theory and Practice of Informatics, 2015.
[[nodiscard]]
static constexpr bool is_prime32(std::uint32_t x) noexcept {
if (x == 2 || x == 3 || x == 5 || x == 7) return true;
if (x % 2 == 0 || x % 3 == 0 || x % 5 == 0 || x % 7 == 0) return false;
if (x < 121) return (x > 1);
std::uint64_t h = x;
h = ((h >> 16) ^ h) * 0x45d9f3b;
h = ((h >> 16) ^ h) * 0x45d9f3b;
h = ((h >> 16) ^ h) & 0xff;
return is_SPRP(x, prime32_bases[h]);
}
} // namespace internal_modint
/// @brief static_modint と dynamic_modint の実装を CRTP によって行うためのクラステンプレート
/// @tparam Modint このクラステンプレートを継承するクラス
template <class Modint>
class modint_base {
public:
/// @brief 保持する値の型
using value_type = std::uint32_t;
/// @brief 0 で初期化します。
constexpr modint_base() noexcept
: m_value{0} {}
/// @brief @c value の剰余で初期化します。
/// @param value 初期化に使う値
template <class SignedIntegral, ENABLE_IF_T((std::is_integral_v<SignedIntegral> && std::is_signed_v<SignedIntegral>))>
constexpr modint_base(SignedIntegral value) noexcept
: m_value{static_cast<value_type>((static_cast<long long>(value) % Modint::mod() + Modint::mod()) % Modint::mod())} {}
/// @brief @c value の剰余で初期化します。
/// @param value 初期化に使う値
template <class UnsignedIntegral, ENABLE_IF_T((std::is_integral_v<UnsignedIntegral> && std::is_unsigned_v<UnsignedIntegral>))>
constexpr modint_base(UnsignedIntegral value) noexcept
: m_value{static_cast<value_type>(value % Modint::mod())} {}
/// @brief 保持している値を取得します。
/// @return 保持している値
[[nodiscard]]
constexpr value_type val() const noexcept {
return m_value;
}
/// @brief 保持している値をインクリメントして、剰余を取ります。
/// @return @c *this
constexpr Modint& operator++() noexcept {
++m_value;
if (m_value == Modint::mod()) {
m_value = 0;
}
return static_cast<Modint&>(*this);
}
/// @brief 保持している値をインクリメントして、剰余を取ります。
/// @return インクリメントする前の値
constexpr Modint operator++(int) noexcept {
auto x = static_cast<const Modint&>(*this);
++*this;
return x;
}
/// @brief 保持している値をデクリメントして、剰余を取ります。
/// @return @c *this
constexpr Modint& operator--() noexcept {
if (m_value == 0) {
m_value = Modint::mod();
}
--m_value;
return static_cast<Modint&>(*this);
}
/// @brief 保持している値をデクリメントして、剰余を取ります。
/// @return デクリメントする前の値
constexpr Modint operator--(int) noexcept {
auto x = static_cast<const Modint&>(*this);
--*this;
return x;
}
/// @brief 保持している値に @c x の持つ値を足して、剰余を取ります。
/// @param x 足す数
/// @return @c *this
constexpr Modint& operator+=(const Modint& x) noexcept {
m_value += x.m_value;
if (m_value >= Modint::mod()) {
m_value -= Modint::mod();
}
return static_cast<Modint&>(*this);
}
/// @brief 保持している値から @c x の持つ値を引いて、剰余を取ります。
/// @param x 引く数
/// @return @c *this
constexpr Modint& operator-=(const Modint& x) noexcept {
m_value -= x.m_value;
if (m_value >= Modint::mod()) {
m_value += Modint::mod();
}
return static_cast<Modint&>(*this);
}
/// @brief 保持している値に @c x の持つ値を掛けて、剰余を取ります。
/// @param x 掛ける数
/// @return @c *this
constexpr Modint& operator*=(const Modint& x) noexcept {
m_value = static_cast<value_type>(static_cast<std::uint64_t>(m_value) * x.m_value % Modint::mod());
return static_cast<Modint&>(*this);
}
/// @brief 保持している値を @c x の持つ値で割って、剰余を取ります。
/// @remark 時間計算量: @f$O(\log x)@f$
/// @param x 割る数
/// @return @c *this
constexpr Modint& operator/=(const Modint& x) noexcept {
return *this *= x.inv();
}
/// @brief 自身のコピーを返します。
/// @return @c *this
[[nodiscard]]
constexpr Modint operator+() const noexcept {
return static_cast<const Modint&>(*this);
}
/// @brief 自身の反数を返します。
/// @return 自身の反数
[[nodiscard]]
constexpr Modint operator-() const noexcept {
return 0 - static_cast<const Modint&>(*this);
}
/// @brief 自身の @c n 乗を返します。
/// @remark 時間計算量: @f$O(\log n)@f$
/// @param n 指数
/// @return 自身の @c n 乗
[[nodiscard]]
constexpr Modint pow(unsigned long long n) const noexcept {
Modint x = 1;
Modint y = static_cast<const Modint&>(*this);
while (n) {
if (n & 1) {
x *= y;
}
y *= y;
n >>= 1;
}
return x;
}
/// @brief 自身の逆数を返します。
/// @remark 時間計算量: @f$O(\log value)@f$
/// @return 自身の逆数
[[nodiscard]]
constexpr Modint inv() const noexcept {
long long a = Modint::mod();
long long b = m_value;
long long x = 0;
long long y = 1;
while (b) {
auto t = a / b;
auto u = a - t * b;
a = b;
b = u;
u = x - t * y;
x = y;
y = u;
}
assert(a == 1 && "The inverse element does not exist.");
x %= Modint::mod();
if (x < 0) {
x += Modint::mod();
}
return x;
}
/// @brief @c x に @c y を足したオブジェクトを返します。
/// @param x 足される数
/// @param y 足す数
/// @return @c x に @c y を足したオブジェクト
[[nodiscard]]
friend constexpr Modint operator+(const Modint& x, const Modint& y) noexcept {
return std::move(Modint{x} += y);
}
/// @brief @c x から @c y を引いたオブジェクトを返します。
/// @param x 引かれる数
/// @param y 引く数
/// @return @c x から @c y を引いたオブジェクト
[[nodiscard]]
friend constexpr Modint operator-(const Modint& x, const Modint& y) noexcept {
return std::move(Modint{x} -= y);
}
/// @brief @c x に @c y を掛けたオブジェクトを返します。
/// @param x 掛けられる数
/// @param y 掛ける数
/// @return @c x に @c y を掛けたオブジェクト
[[nodiscard]]
friend constexpr Modint operator*(const Modint& x, const Modint& y) noexcept {
return std::move(Modint{x} *= y);
}
/// @brief @c x を @c y で割ったオブジェクトを返します。
/// @param x 割られる数
/// @param y 割る数
/// @return @c x を @c y で割ったオブジェクト
[[nodiscard]]
friend constexpr Modint operator/(const Modint& x, const Modint& y) noexcept {
return std::move(Modint{x} /= y);
}
/// @brief @c x と @c y の保持する値が等しいかどうかを調べます。
/// @return @c x と @c y の保持する値が等しければ @c true 、そうでなければ @c false
[[nodiscard]]
friend constexpr bool operator==(const Modint& x, const Modint& y) noexcept {
return x.m_value == y.m_value;
}
/// @brief @c x と @c y の保持する値が等しくないかどうかを調べます。
/// @return @c x と @c y の保持する値が等しければ @c false 、そうでなければ @c true
[[nodiscard]]
friend constexpr bool operator!=(const Modint& x, const Modint& y) noexcept {
return !(x == y);
}
/// @brief 入力ストリームから符号付き整数を読み取り、 @c x に格納します。
/// @tparam CharT 入力ストリームの文字型
/// @tparam Traits 入力ストリームの文字トレイト
/// @param is 入力ストリーム
/// @param x 入力を受け取るオブジェクト
/// @return @c is
template <class CharT, class Traits>
friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Modint& x) {
long long tmp;
is >> tmp;
x = tmp;
return is;
}
/// @brief 出力ストリームに @c x の保持する値を出力します。
/// @tparam CharT 出力ストリームの文字型
/// @tparam Traits 出力ストリームの文字トレイト
/// @param os 出力ストリーム
/// @param x 出力するオブジェクト
/// @return @c os
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Modint& x) {
os << x.val();
return os;
}
protected:
value_type m_value;
};
/// @brief コンパイル時に法が決まるとき、四則演算において自動で mod を取るクラス
/// @tparam Mod 法
template <std::uint32_t Mod>
class static_modint : public modint_base<static_modint<Mod>> {
static_assert(Mod > 0 && Mod <= std::numeric_limits<std::uint32_t>::max() / 2);
private:
using base_type = modint_base<static_modint<Mod>>;
public:
using typename base_type::value_type;
/// @brief 法を取得します。
/// @return 法
[[nodiscard]]
static constexpr value_type mod() noexcept {
return Mod;
}
/// @brief 0 で初期化します。
constexpr static_modint() noexcept
: base_type{} {}
/// @brief @c value の剰余で初期化します。
/// @param value 初期化に使う値
template <class SignedIntegral, ENABLE_IF_T(std::is_integral_v<SignedIntegral>)>
constexpr static_modint(SignedIntegral value) noexcept
: base_type{value} {}
/// @brief 自身の逆数を返します。
/// @remark 時間計算量: @f$O(\log value)@f$
/// @return 自身の逆数
[[nodiscard]]
constexpr static_modint inv() const noexcept {
if constexpr (internal_modint::is_prime32(Mod)) {
assert(this->m_value != 0 && "The inverse element of zero does not exist.");
return this->pow(Mod - 2);
} else {
return base_type::inv();
}
}
};
/// @brief 実行時に法が決まるとき、四則演算において自動で mod を取るクラス
/// @tparam ID このIDごとに法を設定することができます
template <int ID>
class dynamic_modint : public modint_base<dynamic_modint<ID>> {
private:
using base_type = modint_base<dynamic_modint<ID>>;
public:
using typename base_type::value_type;
/// @brief 法を取得します。
/// @return 法
[[nodiscard]]
static value_type mod() noexcept {
return modulus;
}
/// @brief 法を設定します。
/// @param m 新しい法
static void set_mod(value_type m) noexcept {
assert(m > 0 && m <= std::numeric_limits<value_type>::max() / 2);
modulus = m;
}
/// @brief 0 で初期化します。
constexpr dynamic_modint() noexcept
: base_type{} {}
/// @brief @c value の剰余で初期化します。
/// @param value 初期化に使う値
template <class SignedIntegral, ENABLE_IF_T(std::is_integral_v<SignedIntegral>)>
constexpr dynamic_modint(SignedIntegral value) noexcept
: base_type{value} {}
private:
inline static value_type modulus = 998244353;
};
using modint998244353 = static_modint<998244353>;
using modint1000000007 = static_modint<1000000007>;
using modint = dynamic_modint<-1>;
#line 8 "test/yosupo/graph/enumerate-triangles.test.cpp"
using mint = modint998244353;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, m;
std::cin >> n >> m;
std::vector<mint> x(n);
for (auto& v : x) std::cin >> v;
Graph<int> g(n);
g.read(m, 0);
mint ans = 0;
enumerate_triangles(g, [&](long long a, long long b, long long c) { ans += x[a] * x[b] * x[c]; });
std::cout << ans << '\n';
}