結果
| 問題 |
No.1484 木に数を書き込む問題 / Just Write Numbers! 2
|
| ユーザー |
Nachia
|
| 提出日時 | 2021-04-19 01:03:55 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 340 ms / 2,000 ms |
| コード長 | 1,050 bytes |
| コンパイル時間 | 1,345 ms |
| コンパイル使用メモリ | 79,368 KB |
| 最終ジャッジ日時 | 2025-01-20 21:54:34 |
|
ジャッジサーバーID (参考情報) |
judge1 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 29 |
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:43:8: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
43 | scanf("%d",&N);
| ~~~~~^~~~~~~~~
main.cpp:46:19: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
46 | int u,v; scanf("%d%d",&u,&v); u--; v--;
| ~~~~~^~~~~~~~~~~~~~
ソースコード
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using ull = unsigned long long;
using ll = long long;
#define rep(i,n) for(int i=0; i<(n); i++)
int N;
vector<vector<int>> E;
vector<int> D;
vector<int> P;
vector<int> ans2;
vector<int> ans;
void dfs(int p){
for(int e:E[p]) if(D[e]==-1){
P[e] = p;
D[e] = D[p]+1;
dfs(e);
}
}
void dfs2(int p){
if(D[P[p]]==-1){
int e=P[p];
D[e]=0;
ans2[e] = ans2[p] + 1;
dfs2(e);
ans2[p] = ans[e] + 1;
}
for(int e:E[p]) if(D[e]==-1){
D[e]=0;
ans2[e] = ans2[p] + 1;
dfs2(e);
ans2[p] = ans[e] + 1;
}
ans[p] = ans2[p];
}
int main(){
scanf("%d",&N);
E.resize(N);
rep(i,N-1){
int u,v; scanf("%d%d",&u,&v); u--; v--;
E[u].push_back(v);
E[v].push_back(u);
}
D.assign(N,-1);
P.assign(N,-1);
D[0]=0; dfs(0);
int s=0; rep(i,N) if(D[s]<D[i]) s=i;
D.assign(N,-1);
P.assign(N,-1);
D[s]=0; dfs(s);
int t=0; rep(i,N) if(D[t]<D[i]) t=i;
printf("%d\n",(N-1)*2-D[t]);
return 0;
}
Nachia