結果
問題 | No.1976 Cut then Connect |
ユーザー |
![]() |
提出日時 | 2022-03-24 19:06:30 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
WA
(最新)
AC
(最初)
|
実行時間 | - |
コード長 | 2,662 bytes |
コンパイル時間 | 2,026 ms |
コンパイル使用メモリ | 176,052 KB |
実行使用メモリ | 16,672 KB |
最終ジャッジ日時 | 2024-09-20 22:35:38 |
合計ジャッジ時間 | 6,820 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | WA * 2 |
other | TLE * 1 -- * 30 |
ソースコード
#include <bits/stdc++.h>using namespace std;struct Edge {int u;int v;int cost;Edge(int a, int b, int c) : u(a), v(b), cost(c) {}};using Graph = vector<vector<Edge>>;vector<int> dp;int max_, max_2;void dfs(const Graph& G, int v, int p, int x, bool flag) {if (x == v) flag = false;for (auto nv : G[v]) {if (nv.v == p) continue;dfs(G, nv.v, v, x, flag);}if (flag) {int max1 = 0, max2 = 0;for (auto c : G[v]) {if (c.v == p) continue;if (max1 < dp[c.v]) {max2 = max1;max1 = dp[c.v];}else if (max2 < dp[c.v]) {max2 = dp[c.v];}}max_ = max(max_, max1 + max2 + 1);dp[v] = max1 + 1;}else {int max1 = 0, max2 = 0;for (auto c : G[v]) {if (c.v == p) continue;if (max1 < dp[c.v]) {max2 = max1;max1 = dp[c.v];}else if (max2 < dp[c.v]) {max2 = dp[c.v];}}max_2 = max(max_2, max1 + max2 + 1);dp[v] = max1 + 1;}if (x == v) dp[v] = 0;}void dfs2(const Graph& G, int v, int p) {for (auto nv : G[v]) {if (nv.v == p) continue;dfs2(G, nv.v, v);};for (auto c : G[v]) {if (c.v == p) continue;dp[v] = max(dp[v], dp[c.v] + 1);}}int main() {int N; cin >> N;Graph G(N);for (int i = 0; i < N - 1; i++) {int a, b;cin >> a >> b;G[a - 1].emplace_back(a - 1, b - 1, 1);G[b - 1].emplace_back(b - 1, a - 1, 1);}bool flag = true;for (int i = 0; i < N; i++) {if (G[i].size() >= 3) flag = false;}if (flag) {cout << N << endl;return 0;}int ans = 0;for (int i = 0; i < N; i++) {dp.assign(N, 0);max_ = 0;max_2 = 0;dfs(G, 0, -1, i, true);ans = max(ans, max_ + max_2);}for (int i = 0; i < N; i++) {dp.assign(N, 0);dfs2(G, i, -1);int max1 = 0, max2 = 0, max3 = 0;for (auto c : G[i]) {if (max1 < dp[c.v]) {max3 = max2;max2 = max1;max1 = dp[c.v];}else if (max2 < dp[c.v]) {max3 = max2;max2 = dp[c.v];}else if (max3 < dp[c.v]) {max3 = dp[c.v];}}ans = max(ans, max1 + max2 + max3 + 1);}cout << ans << endl;}