Algorithmic Problem Solving: Simulations, Matrix Calculations, and Graph Traversal

Analyzing Core Algorithmic Challenges

This document explores a series of computational tasks ranging from basic arithmetic simulations to complex graph theory applications. Each segment presents a unique logic puzzle requiring precise implementation.

Basic Output and Division Logic

The initial challenge requires generating a fixed motivational string. While trivial, it sets the standard for formatted output.

#include <iostream>
#include <string>

int main() {
    std::cout << "Success achieved! Starting now!\n";
    return 0;
}

A subsequent task involves calculating integer quotients given a total quantity and a divisor representing capacity. The result is simply the floor of the division operation.

#include <iostream>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int inventory_total, slot_capacity;
    cin >> inventory_total >> slot_capacity;

    int full_slots = inventory_total / slot_capacity;
    cout << full_slots << "\n";

    return 0;
}

Conditional Access Scenarios

Access control systems often rely on multiple criteria. Consider a library entry simulation where individuals are evaluated based on age thresholds (a and b) relative to their current status times (x and y).

The logic dictates four primary outcomes: 1. Both high: Unrestricted access. 2. Both low: Denied access. 3. One high, one low: Conditional routing to specific counters. 4. Mixed states: Specific warning messages based on which condition failed.

#include <iostream>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int threshold_high, threshold_mid, val_x, val_y;
    cin >> threshold_high >> threshold_mid >> val_x >> val_y;

    if (val_x >= threshold_high && val_y >= threshold_high) {
        cout << val_x << "-Y " << val_y << "-Y\n";
        cout << "welcome_to_library\n";
    } else if (val_x < threshold_high && val_y < threshold_high) {
        cout << val_x << "-N " << val_y << "-N\n";
        cout << "try_again_later\n";
    } else if (val_x >= threshold_mid && val_y < threshold_high) {
        cout << val_x << "-Y " << val_y << "-Y\n";
        cout << "queue_counter_1\n";
    } else if (val_x < threshold_high && val_y >= threshold_mid) {
        cout << val_x << "-Y " << val_y << "-Y\n";
        cout << "queue_counter_2\n";
    } else {
        bool x_ok = val_x >= threshold_high;
        bool y_ok = val_y >= threshold_high;
        
        if (x_ok) cout << val_x << "-Y " << val_y << "-N\n";
        else cout << val_x << "-N " << val_y << "-Y\n";
        
        cout << ((y_ok ? 2 : 1) << ": welcome_to_library\n");
    }

    return 0;
}

Mathematical Computations

Some problems require recursive-like mathematical calculations. Here, we compute the factorial of the sum of two inputs.

#include <iostream>
#include <cstdint>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int input_a, input_b;
    cin >> input_a >> input_b;
    
    int target_sum = input_a + input_b;
    
    uint64_t product_result = 1;
    while (target_sum > 0) {
        product_result *= target_sum;
        target_sum--;
    }

    cout << product_result << "\n";

    return 0;
}

Grid and State Manipulation

Dice rolling simulations involve tracking available slots on a grid over multiple rounds. The goal is to fill empty spots in a column-first manner for each player row.

#include <iostream>
#include <vector>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    vector<int> rolls(7, 0);
    vector<vector>> occupied(7, vector<bool>(7, false));

    for (int i = 1; i <= 6; ++i) {
        int roll_val;
        cin >> roll_val;
        rolls[i] = roll_val;
        occupied[i][roll_val] = true;
    }

    int rounds;
    cin >> rounds;
    --rounds; // Adjust count based on initial input logic

    while (rounds--) {
        for (int row = 1; row <= 6; ++row) {
            for (int col = 6; col >= 1; --col) {
                if (!occupied[row][col]) {
                    occupied[row][col] = true;
                    break;
                }
            }
        }
    }

    for (int row = 1; row <= 6; ++row) {
        for (int col = 6; col >= 1; --col) {
            if (!occupied[row][col]) {
                cout << col << (row == 6 ? "" : " ");
                break;
            }
        }
    }
    cout << endl;

    return 0;
}
</bool></vector></int>

String Processing Logic

Processing strings based on character parity (even or odd ASCII values) allows for pattern matching across different inputs. When adjacent characters share the same parity, the larger character is selected.

#include <iostream>
#include <string>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    string input_str[2];
    cin >> input_str[0] >> input_str[1];

    string extracted_seq[2];

    for (int idx = 0; idx < 2; ++idx) {
        for (size_t j = 1; j < input_str[idx].length(); ++j) {
            if (input_str[idx][j] % 2 == input_str[idx][j - 1] % 2) {
                char best_char = max(input_str[idx][j], input_str[idx][j - 1]);
                extracted_seq[idx] += best_char;
            }
        }
    }

    if (extracted_seq[0] == extracted_seq[1]) {
        cout << extracted_seq[0] << "\n";
    } else {
        cout << extracted_seq[0] << "\n" << extracted_seq[1] << "\n";
    }

    return 0;
}

Set Theory and Grid Coverage

Calculating safe zones on a matrix affected by row and column attacks utilizes the Principle of Inclusion-Exclusion. The number of compromised cells equals the union of attacked rows and columns.

using namespace std;

int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);

int r, c, queries;
cin >> r >> c >> queries;

set<int> bad_rows, bad_cols;

for (int q = 0; q < queries; ++q) {
    int type, val;
    cin >> type >> val;
    if (type == 0) bad_rows.insert(val);
    else bad_cols.insert(val);
}

long long total_cells = (long long)r * c;
long long covered_rows = (long long)c * bad_rows.size();
long long covered_cols = (long long)r * bad_cols.size();
long long intersection = (long long)bad_rows.size() * bad_cols.size();

long long result = total_cells - (covered_rows + covered_cols - intersection);

cout << result << "\n";

return 0;

}


### Sorting and Filtering Data

When processing personnel recommendations, sorting records by score allows prioritizing candidates who meet strict criteria, with fallback options for those close to the threshold.

#include #include #include

using namespace std;

int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);

int n, k_limit, s_score;
cin >> n >> k_limit >> s_score;

vector<vector>> height_buckets(300);

for (int i = 0; i < n; ++i) {
    int h, s;
    cin >> h >> s;
    if (h >= 175) {
        height_buckets[h].push_back(s);
    }
}

int qualified_count = 0;

for (int h = 175; h <= 290; ++h) {
    auto& scores = height_buckets[h];
    sort(scores.begin(), scores.end(), greater<int>());

    int k_buffer = k_limit;
    for (int val : scores) {
        if (val >= s_score) {
            qualified_count++;
        } else if (k_buffer > 0) {
            qualified_count++;
            k_buffer--;
        } else {
            break; 
        }
    }
}

cout << qualified_count << "\n";

return 0;

}


### Stack-Based Assembly Simulation

Complex state machines can be modeled using stacks. In this scenario, materials (pine needles) are pushed onto a container stack when they do not fit the current assembly sequence immediately. The logic ensures non-increasing order for valid branches until capacity limits force a reset.

#include #include #include #include

using namespace std;

int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);

int m, capacity_n, limit_k;
cin >> m >> capacity_n >> limit_k; // Note: Renamed vars to avoid collision with standard types where possible

vector<int> raw_materials(n);
for (auto &mat : raw_materials) cin >> mat;

stack<int> buffer_stack;
vector<vector>> finished_branches;
vector<int> current_branch;

int material_idx = 0;
int remaining_materials = n;

while (remaining_materials > 0) {
    bool branch_created = false;

    // Check top of stack
    while (!buffer_stack.empty()) {
        if (current_branch.empty() || buffer_stack.top() <= current_branch.back()) {
            current_branch.push_back(buffer_stack.top());
            buffer_stack.pop();
            
            if ((int)current_branch.size() == limit_k) {
                finished_branches.push_back(current_branch);
                remaining_materials -= limit_k;
                current_branch.clear();
                branch_created = true;
                break;
            }
        } else {
            break;
        }
    }
    if (branch_created) continue;

    // Pull from raw materials
    while (material_idx < n) {
        int next_item = raw_materials[material_idx];
        
        if (current_branch.empty() || next_item <= current_branch.back()) {
            current_branch.push_back(next_item);
            material_idx++;
        } else {
            if ((int)buffer_stack.size() == m) {
                finished_branches.push_back(current_branch);
                remaining_materials -= current_branch.size();
                current_branch.clear();
                branch_created = true;
                break;
            }
            buffer_stack.push(next_item);
            material_idx++;
        }

        if ((int)current_branch.size() == limit_k) {
            finished_branches.push_back(current_branch);
            remaining_materials -= current_branch.size();
            current_branch.clear();
            branch_created = true;
            break;
        }
    }
    if (branch_created) continue;

    // Flush remaining
    if (!current_branch.empty()) {
        finished_branches.push_back(current_branch);
        remaining_materials -= current_branch.size();
        current_branch.clear();
    }
}

for (const auto& branch : finished_branches) {
    for (size_t i = 0; i < branch.size(); ++i) {
        cout << branch[i] << (i == branch.size() - 1 ? "" : " ");
    }
    cout << "\n";
}

return 0;

}


### Schedule Interval Management

Managing busy intervals requires discretizing time accuartely. By multiplying time granularity, we can handle half-second steps effectively, marking required work hours and checkpoints to determine free periods.

#include #include #include

using namespace std;

void print_time(int seconds) { printf("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, seconds % 60); }

int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);

int shifts_count;
cin >> shifts_count;

const int DAY_SECONDS = 24 * 60 * 60;
vector<int> demand_flags(DAY_SECONDS, 0);
vector<int> checkpoint_flags(DAY_SECONDS * 10, 0);

for (int i = 0; i < shifts_count; ++i) {
    int h1, m1, s1, h2, m2, s2;
    char sep;
    cin >> h1 >> sep >> m1 >> sep >> s1 >> sep;
    cin >> h2 >> sep >> m2 >> sep >> s2;

    int t_start = h1 * 3600 + m1 * 60 + s1;
    int t_end = h2 * 3600 + m2 * 60 + s2;

    for (int sec = t_start + 1; sec < t_end; ++sec) {
        demand_flags[sec] = 1;
    }
    for (int sec = t_start; sec < t_end; ++sec) {
        checkpoint_flags[sec * 10 + 5] = 1;
    }
}

for (int sec = 0; sec < DAY_SECONDS; ++sec) {
    int curr = sec;
    
    // Extend interval forward
    while (curr + 1 < DAY_SECONDS && demand_flags[curr + 1] == 0) {
        curr++;
        if (checkpoint_flags[curr * 10 + 5]) break;
    }

    // Skip if not a valid gap or too short
    if (checkpoint_flags[sec * 10 + 5] || (curr - sec) < 1) {
        continue;
    }

    print_time(sec);
    printf(" - ");
    print_time(curr);
    printf("\n");

    sec = curr;
}

return 0;

}


### Tree Path Optimization

To minimize travel distance in a tree structure where multiple nodes need servicing, we consider that every edge except those on the longest path from the root to a leaf will be traversed twice (once down, once up). We track the maximum single-travel depth dynamically as nodes are queried.

#include #include #include #include

using namespace std;

int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);

int n, q;
cin >> n >> q;

vector<int> parent(n + 1, -1), depth(n + 1, 0);
int root_node = -1;

for (int i = 1; i <= n; ++i) {
    int p;
    cin >> p;
    if (p == -1) {
        root_node = i;
    } else {
        parent[i] = p;
    }
}

set<int> visited_nodes;
int max_dist = 0;

auto dfs_update = [&](auto&& self, int u, int cur_dis) -> int {
    if (visited_nodes.count(u)) {
        max_dist = max(max_dist, depth[u] + cur_dis);
        return 2 * cur_dis;
    }
    int res = self(self, parent[u], cur_dis + 1);
    depth[u] = depth[parent[u]] + 1; // Root depth handling implicit via parent init
    visited_nodes.insert(u);
    return res;
};

visited_nodes.insert(root_node);

long long total_cost = 0;
while (q--) {
    int node_req;
    cin >> node_req;
    total_cost += dfs_update(dfs_update, node_req, 0);
    cout << total_cost - max_dist << "\n";
}

return 0;

}


### All-Pairs Shortest Path Analysis

Identifying optimal social connections requires finding the farthest reachable person of the opposite gender. Using the Floyd-Warshall algorithm, we preprocess the graph to get distances between all pairs, then aggregate results by gender constraints.

#include #include #include &lt>climits>

using namespace std;

int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);

int n;
cin >> n;

const int INF = INT_MAX / 2;
vector<int> gender_map(n + 1);
vector<vector>> dist(n + 1, vector<int>(n + 1, INF));

for (int i = 1; i <= n; ++i) {
    char type;
    int k;
    cin >> type >> k;
    gender_map[i] = (type == 'F' ? 0 : 1);
    
    for (int j = 0; j < k; ++j) {
        int neighbor;
        char sep;
        int weight;
        cin >> neighbor >> sep >> weight;
        dist[i][neighbor] = weight;
    }
    dist[i][i] = 0;
}

// Floyd-Warshall Implementation
for (int k = 1; k <= n; ++k) {
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (i != j) {
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }
}

vector<int> max_dists(n + 1, -INF);
for (int i = 1; i <= n; ++i) {
    for (int j = i + 1; j <= n; ++j) {
        if (gender_map[i] != gender_map[j]) {
            max_dists[i] = max(max_dists[i], dist[j][i]);
            max_dists[j] = max(max_dists[j], dist[i][j]);
        }
    }
}

vector<int> candidates[2];
int min_threshold[2] = {INF, INF};

for (int i = 1; i <= n; ++i) {
    int t = gender_map[i];
    if (min_threshold[t] > max_dists[i]) {
        min_threshold[t] = max_dists[i];
        candidates[t].clear();
        candidates[t].push_back(i);
    } else if (max_dists[i] == min_threshold[t]) {
        candidates[t].push_back(i);
    }
}

for (int t = 0; t < 2; ++t) {
    for (size_t i = 0; i < candidates[t].size(); ++i) {
        cout << candidates[t][i] << (i == candidates[t].size() - 1 ? "" : " ");
    }
    if(!candidates[t].empty()) cout << "\n";
}

return 0;

}

Tags: C++ simulation Floyd-Warshall Depth-First Search Greedy Algorithm

Posted on Sun, 23 Aug 2026 16:35:55 +0000 by simplyi