Question description
There are cities, each numbered from . There are also roads, with the -th road connecting cities and bidirectionally. It is possible to travel between any two cities using some roads.
Now, you can freely choose integers () and build a single new road that connects city and city bidirectionally. Then, the following value is considered as the score:
- The number of roads traveled in a route that returns to the same city without passing the same road twice (this value is uniquely determined).
Output the maximum possible score.
Constraints
It is possible to travel between any two cities using some roads
All inputs are integers
Input
Output
the maximum possible score
Approach
This question pertains to finding the longest path in a connected, undirected graph , also known as the diameter of . The diameter of a graph is the maximum vertex-to-vertex distance in the graph. To find the diameter of , follow these steps:
- Choose any vertex and run Depth-First Search (DFS) with as the starting vertex. The farthest vertex reached from is denoted as .
- Run DFS again with as the starting vertex and find the farthest vertex reached, denoted as .
- The diameter of is the longest path between and .
Complexity Analysis
- time complexity :
Solution
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
c
const int INF = (1 << 29);
vector<vector<int>> G(1 << 18);
vector<int> C(1 << 18), P(1 << 18), D(1 << 18);
int N;
void bfs(int s) {
for (int i = 1; i <= N ; i++) {
C[i] = 0;
D[i] = INF;
P[i] = -1;
}
C[s] = 1;
D[s] = 0;
P[s] = -1;
queue<int> q;
q.push(s);
while (!q.empty()) {
int u = q.front); q.pop();
for (int v : G[u]) {
if(C[v] == 0) {
C[v] = 1;
D[v] = D[u] + 1;
q.push(v);
}
}
C[u] = 2;
}
}
int main(){
cin >> N;
for (int i = 0; i < N; i++) {
int u, v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
bfs(1);
int md = -1, idx = -1;
for (int i = 1; i <= N; i++) {
if (D[i] > md) {
md = D[i];
idx = i;
}
}
bfs(idx);
int ans = -1;
for (int i = 1; i <=N; i++) {
ans = max(ans, D[i]);
}
cout << ans + 1<< endl;
return 0;
}