Skip to content

Conversation

@vingoel26
Copy link
Contributor

@vingoel26 vingoel26 commented Oct 20, 2025

🎯 Problem Information

Problem Name: Building Roads
Category: Graphs (Connected Components, DFS)
CSES Link: https://cses.fi/problemset/task/1666/
Difficulty: Medium
#110

📝 Description

This PR adds the C++ solution for the Building Roads problem from the CSES problem set.
The task is to determine the minimum number of new roads required to make all cities connected and list the specific roads that need to be built.


🧩 Solution Approach

  • Algorithm Used: Depth-First Search (DFS) to find connected components.
  • Time Complexity: O(n + m) — each node and edge is visited once.
  • Space Complexity: O(n + m) — for adjacency list and visited array.
  • Key Insights:
    • Each connected component must be linked to another to make the graph fully connected.
    • The minimum roads required = (number of components - 1).
    • We can connect representatives of each component sequentially to ensure full connectivity.

✅ Checklist

Please ensure your PR meets these requirements:

Code Quality

  • Solution follows the required template format
  • Code is clean and well-commented
  • Variable names are descriptive
  • Proper error handling for edge cases

Testing

  • Solution passes all CSES test cases
  • Tested with custom edge cases
  • Handles large input constraints efficiently
  • No runtime errors or timeouts

Documentation

  • Added solution to appropriate category folder (graphs/)
  • File name follows naming convention (building_roads.cpp)
  • Added brief comment explaining the approach
  • Updated any relevant documentation if needed

Style Guide

  • Uses required headers (#include <bits/stdc++.h>)
  • Includes fast I/O optimization
  • Uses appropriate data types (long long for large numbers)
  • Follows competitive programming best practices

🏷️ Type of Change

  • 🐛 Bug fix (fixes an existing solution)
  • ✨ New problem solution
  • 📚 Documentation improvement
  • 🔧 Code optimization/refactoring
  • 🎃 Hacktoberfest contribution

🧪 Testing Details

Test Cases Used:

Input:
6 3
1 2
2 3
4 5

Expected Output:
2
3 4
5 6
Explanation:
There are 3 connected components: {1, 2, 3}, {4, 5}, {6}.
We need to add 2 roads to connect them all, e.g., (3–4) and (5–6).


📸 Screenshots (if applicable)

verified on CSES judge with AC (Accepted).
image


📎 Additional Notes

  • The solution uses recursive DFS with a visited array and adjacency list.
  • Each connected component's representative node is stored to later connect them sequentially.
  • Edge case handled: when the graph is already connected (output = 0).

For Maintainers:

  • Code review completed
  • Solution verified on CSES judge
  • Documentation updated if needed
  • Labels applied appropriately

@ks-iitjmu ks-iitjmu requested a review from Copilot October 20, 2025 12:47
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR implements a C++ solution for the "Building Roads" problem from CSES, which finds the minimum number of roads needed to connect all cities in a graph. The solution uses Depth-First Search (DFS) to identify connected components and then connects their representatives sequentially.

  • Uses iterative DFS to find connected components and avoid recursion depth issues
  • Calculates minimum roads needed as (number of components - 1)
  • Outputs specific road connections between component representatives

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.


// Read number of cities (nodes) and existing roads (edges)
int num_nodes, num_edges;
if (!(cin >> num_nodes >> num_edges)) return 0;
Copy link

Copilot AI Oct 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The input validation should handle the case where input fails more explicitly. Consider using proper error handling or removing this check entirely since competitive programming problems typically guarantee valid input.

Suggested change
if (!(cin >> num_nodes >> num_edges)) return 0;
cin >> num_nodes >> num_edges;

Copilot uses AI. Check for mistakes.
}

// visited[i] == true means node i has been visited in component discovery
vector<char> visited(num_nodes + 1, false);
Copy link

Copilot AI Oct 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Using vector<char> instead of vector<bool> is unconventional for boolean flags. Consider using vector<bool> which is specifically designed for boolean values and provides space optimization.

Suggested change
vector<char> visited(num_nodes + 1, false);
vector<bool> visited(num_nodes + 1, false);

Copilot uses AI. Check for mistakes.
int component_count = static_cast<int>(representatives.size());

// Minimum roads required to connect all components = components - 1
int roads_to_add = max(0, component_count - 1);
Copy link

Copilot AI Oct 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The max(0, component_count - 1) is unnecessary since component_count will always be at least 1 (when num_nodes >= 1). This can be simplified to component_count - 1.

Suggested change
int roads_to_add = max(0, component_count - 1);
int roads_to_add = component_count - 1;

Copilot uses AI. Check for mistakes.
@ks-iitjmu ks-iitjmu added enhancement New feature or request good first issue Good for newcomers hacktoberfest Issues/PRs for Hacktoberfest participation hacktoberfest-accepted Approved PRs for Hacktoberfest hacktoberfest_2025 Hacktoberfest 2025 specific contributions medium Medium difficulty problems labels Oct 20, 2025
@ks-iitjmu ks-iitjmu linked an issue Oct 20, 2025 that may be closed by this pull request
9 tasks
@ks-iitjmu ks-iitjmu added the category: graph Graph algorithm problems label Oct 20, 2025
@ks-iitjmu ks-iitjmu merged commit a307e86 into ks-iitjmu:main Oct 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

category: graph Graph algorithm problems enhancement New feature or request good first issue Good for newcomers hacktoberfest Issues/PRs for Hacktoberfest participation hacktoberfest_2025 Hacktoberfest 2025 specific contributions hacktoberfest-accepted Approved PRs for Hacktoberfest medium Medium difficulty problems

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[NEW] Add solution for Building Roads

2 participants