0% found this document useful (0 votes)
38 views2 pages

Codeforces Solution Infected Tree

The document contains a C++ program that implements a depth-first search (DFS) algorithm to analyze a tree structure. It calculates a specific depth value based on the number of children each node has and outputs the difference between the total number of nodes and this depth value. The program is designed to handle multiple test cases as specified by the user.

Uploaded by

Amritansha Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views2 pages

Codeforces Solution Infected Tree

The document contains a C++ program that implements a depth-first search (DFS) algorithm to analyze a tree structure. It calculates a specific depth value based on the number of children each node has and outputs the difference between the total number of nodes and this depth value. The program is designed to handle multiple test cases as specified by the user.

Uploaded by

Amritansha Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include<vector>

using namespace std;

void dfs(int u, int parent, int depth, int &d, const vector<vector<int>> &G) {

int child_count = 0;

for (int neighbor : G[u]) {

if (neighbor != parent) {

child_count++;

dfs(neighbor, u, depth + 1, d, G);

if (child_count == 0) {

d = min(d, depth * 2 - 1);

} else if (child_count == 1) {

d = min(d, depth * 2);

void solve() {

int n;

cin >> n;

int d = 1e9;

vector<vector<int>> G(n);

for (int i = 1, u, v; i < n; i++) {

cin >> u >> v;

u--;

v--;

G[u].push_back(v);

G[v].push_back(u);

dfs(0, -1, 1, d, G);


cout << n - d << endl;

int main() {

int t;

cin >> t;

while (t--) {

solve();

return 0;

You might also like