diff --git a/Luogu/T262837/T262837.cpp b/Luogu/T262837/T262837.cpp new file mode 100644 index 00000000..54a50e09 --- /dev/null +++ b/Luogu/T262837/T262837.cpp @@ -0,0 +1,119 @@ +#include +#include +#include +#include +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 1005; + +int n, m, color[N], ans; +int cnt, id[N]; +bool vis[N]; +std::vector g[N]; +std::unordered_set p[N]; + +bool dfs1(int u, int c) { + color[u] = c; + + for (int v : g[u]) { + if (color[v]) { + if (color[v] == c) return false; + } else if (!dfs1(v, 3 - c)) { + return false; + } + } + + return true; +} + +bool check() { + for (int i = 1; i <= n; i++) { + if (!color[i]) { + if (!dfs1(i, 1)) return false; + } + } + + return true; +} + +void dfs2(int u, int x) { + id[u] = x; + p[x].insert(u); + + for (int v : g[u]) { + if (!id[v]) dfs2(v, x); + } +} + +int bfs(int x) { + std::fill_n(vis, N, false); + + int res = 0; + + std::queue> q; + + q.emplace(x, 0); + vis[x] = true; + + while (!q.empty()) { + auto e = q.front(); + q.pop(); + + int u = e.first, + w = e.second; + + res = std::max(res, w); + + for (int v : g[u]) { + if (vis[v]) continue; + vis[v] = true; + + q.emplace(v, w + 1); + } + } + + return res; +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n >> m; + + for (int i = 1, u, v; i <= m; i++) { + cin >> u >> v; + + g[u].emplace_back(v); + g[v].emplace_back(u); + } + + if (!check()) { + cout << -1 << endl; + + exit(0); + } + + for (int i = 1; i <= n; i++) { + if (!id[i]) dfs2(i, ++cnt); + } + + for (int i = 1; i <= cnt; i++) { + int res = 0; + + for (const int &x : p[i]) { + res = std::max(res, bfs(x)); + } + + ans += res; + } + + cout << ans << endl; + + return 0; +} diff --git a/Luogu/T262837/samples/merge.in b/Luogu/T262837/samples/merge.in new file mode 100644 index 00000000..efadb997 --- /dev/null +++ b/Luogu/T262837/samples/merge.in @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4322b1a6e8061bed6b47bf74bea7c4ebc751a08e1e20f09e6c4e26d99502ccc1 +size 426395 diff --git a/Luogu/T262837/samples/merge.out b/Luogu/T262837/samples/merge.out new file mode 100644 index 00000000..15174b3c --- /dev/null +++ b/Luogu/T262837/samples/merge.out @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2218c54ac6a0d40e422f1e643c5df24bcbbe62f33ffe335ca2501dc36629c402 +size 4