Algorithmic Problem Solving: Core Competitive Programming Patterns

This routine processes three integer values and computes their aggregate sum. The logic determines whether the total meets or exceeds a fixed boundary (180), outputting a binary decision accordingly. The implementation focuses on streamlined input/output handling and conditional branching.

#include <iostream>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int valA, valB, valC;
    if (cin >> valA >> valB >> valC) {
        int total = valA + valB + valC;
        if (total >= 180) {
            cout << "NO" << '\n';
        } else {
            cout << "YES" << '\n';
        }
    }
    return 0;
}

Given two strings composed of uppercase alphabetic characters, this algorithm calculates the product of each character's positional value (A=1, B=2, ... Z=26). It then compares the modular residues of both products when divided by 47. Matching residues indicate alignment, triggering a specific action.

#include <iostream>
#include <string>

using namespace std;

long long computePositionalProduct(const string& sequence) {
    long long product = 1;
    for (char ch : sequence) {
        product *= (static_cast<long long>(ch) - 'A' + 1);
    }
    return product;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string groupA, groupB;
    cin >> groupA >> groupB;

    long long prodA = computePositionalProduct(groupA);
    long long prodB = computePositionalProduct(groupB);

    if (prodA % 47 == prodB % 47) {
        cout << "GO" << '\n';
    } else {
        cout << "STAY" << '\n';
    }
    return 0;
}

This task applies fixed coefficients to three input parameters to derive a composite score. The weights (0.2, 0.3, and 0.5) sum to unity, ensuring a normalized weighted average output.

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    double metricA, metricB, metricC;
    cin >> metricA >> metricB >> metricC;

    double finalScore = metricA * 0.2 + metricB * 0.3 + metricC * 0.5;
    cout << fixed << setprecision(6) << finalScore << '\n';
    return 0;
}

For multiple independent queries, the solution counts the total number of prime integers less than or equal to a given limit. The primality test utilizes trial division up to the square root of the candidate number, optimizing the verification process.

#include <iostream>
#include <cmath>

using namespace std;

bool isPrimeCandidate(int num) {
    if (num < 2) return false;
    if (num == 2) return true;
    if (num % 2 == 0) return false;
    int limit = static_cast<int>(sqrt(num));
    for (int divisor = 3; divisor <= limit; divisor += 2) {
        if (num % divisor == 0) return false;
    }
    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int queryCount;
    cin >> queryCount;
    while (queryCount--) {
        int upperBound;
        cin >> upperBound;
        int primeCounter = 0;
        for (int candidate = 2; candidate <= upperBound; ++candidate) {
            if (isPrimeCandidate(candidate)) {
                ++primeCounter;
            }
        }
        cout << primeCounter << '\n';
    }
    return 0;
}

This problem calculates the minimum travel distance between two locations when a direct route or a portal jump is available. By normalizing the coordinate pairss and evaluating both the direct traversal and the combined portal approach, the algorithm selects the optimal path length.

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int pointA, pointB, portalX, portalY;
    cin >> pointA >> pointB >> portalX >> portalY;

    // Normalize endpoints
    if (pointA > pointB) swap(pointA, pointB);
    if (portalX > portalY) swap(portalX, portalY);

    int directCost = pointB - pointA;
    int portalCost = abs(pointA - portalX) + abs(pointB - portalY);

    cout << min(directCost, portalCost) << '\n';
    return 0;
}

When integrating a new value into an existing sorted dataset, the approach simply appends the incoming element and reapplies a standard sorting routine. This guarantees monotonic ordering with minimal implementation overhead.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    size_t elementCount;
    cin >> elementCount;

    vector<int> dataset(elementCount);
    for (size_t i = 0; i < elementCount; ++i) {
        cin >> dataset[i];
    }

    int incomingValue;
    cin >> incomingValue;
    dataset.push_back(incomingValue);

    sort(dataset.begin(), dataset.end());

    for (size_t i = 0; i < dataset.size(); ++i) {
        cout << dataset[i] << (i == dataset.size() - 1 ? "" : " ");
    }
    cout << '\n';
    return 0;
}

The objective is to accumulate a target resource amount starting from a root node, while minimizing the maximum difficulty encountered along the traversal path. A priority queue manages unvisited adjacent nodes, always expanding the route with the lowest immediate cost until the required threshold is met.

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

struct Edge {
    int weight;
    int target;
    bool operator>(const Edge& other) const {
        return weight > other.weight;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int nodeCount, targetResource;
    cin >> nodeCount >> targetResource;

    vector<int> nodeValues(nodeCount + 1, 0);
    for (int i = 2; i <= nodeCount; ++i) {
        cin >> nodeValues[i];
    }

    vector<vector<Edge>> adjacency(nodeCount + 1);
    for (int i = 0; i < nodeCount - 1; ++i) {
        int u, v, cost;
        cin >> u >> v >> cost;
        adjacency[u].push_back({cost, v});
        adjacency[v].push_back({cost, u});
    }

    priority_queue<Edge, vector<Edge>, greater<Edge>> frontier;
    frontier.push({0, 1});
    
    vector<bool> visited(nodeCount + 1, false);
    int collected = 0;
    int maxDifficulty = 0;

    while (!frontier.empty()) {
        Edge current = frontier.top();
        frontier.pop();

        if (visited[current.target]) continue;
        visited[current.target] = true;
        maxDifficulty = max(maxDifficulty, current.weight);
        collected += nodeValues[current.target];

        if (collected >= targetResource) break;

        for (const auto& neighbor : adjacency[current.target]) {
            if (!visited[neighbor.target]) {
                frontier.push({neighbor.weight, neighbor.target});
            }
        }
    }

    cout << maxDifficulty << '\n';
    return 0;
}

Given a sequence of elevation values, the goal is to compute the total material required to level a road. By iterating through the array and summing only the positive differences between consecutive elevations, the algorithm accounts for upward transitions while downward slopes are naturally covered by prior leveling operations.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    size_t segmentCount;
    cin >> segmentCount;

    vector<int> elevations(segmentCount);
    for (size_t i = 0; i < segmentCount; ++i) {
        cin >> elevations[i];
    }

    int operations = elevations[0];
    for (size_t i = 1; i < segmentCount; ++i) {
        if (elevations[i] > elevations[i - 1]) {
            operations += elevations[i] - elevations[i - 1];
        }
    }

    cout << operations << '\n';
    return 0;
}

This optimization identifies redundant monetary values within a system. By sorting the denominations and using a boolean sieve to mark reachable sums, the algorithm filters out any value that can already be constructed from smaller available units, yielding the minimal essential set.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int testCaseCount;
    cin >> testCaseCount;
    while (testCaseCount--) {
        int currencyCount;
        cin >> currencyCount;

        vector<int> denominations(currencyCount);
        for (int i = 0; i < currencyCount; ++i) {
            cin >> denominations[i];
        }
        sort(denominations.begin(), denominations.end());

        int maxValue = denominations.back();
        vector<bool> reachable(maxValue + 1, false);
        reachable[0] = true;

        int essentialCount = 0;
        for (int val : denominations) {
            if (!reachable[val]) {
                ++essentialCount;
                for (int j = 0; j + val <= maxValue; ++j) {
                    if (reachable[j]) reachable[j + val] = true;
                }
            }
        }

        cout << essentialCount << '\n';
    }
    return 0;
}

Given a linear arrangement with weighted elements, the algorithm locates an optimal insertion point to minimize the absolute imbalance between left and right cumulative moments. Precomputing prefix and suffix torque values allows efficient evaluation of each candidate position in linear time.

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int arraySize;
    cin >> arraySize;

    vector<long long> weights(arraySize + 1);
    for (int i = 1; i <= arraySize; ++i) {
        cin >> weights[i];
    }

    int pivot, addPos, addWeight, newWeight;
    cin >> pivot >> addPos >> addWeight >> newWeight;

    auto calculateTorque = [&](int center) -> long long {
        long long left = 0, right = 0;
        for (int i = 1; i < center; ++i) left += weights[i] * (center - i);
        for (int i = center + 1; i <= arraySize; ++i) right += weights[i] * (i - center);
        return left - right;
    };

    long long baseDiff = abs(calculateTorque(pivot));
    // Apply initial addition
    if (addPos < pivot) {
        baseDiff = abs(calculateTorque(pivot) - (pivot - addPos) * addWeight);
    } else if (addPos > pivot) {
        baseDiff = abs(calculateTorque(pivot) + (addPos - pivot) * addWeight);
    }

    int bestPos = pivot;
    long long minDiff = baseDiff;

    for (int i = 1; i <= arraySize; ++i) {
        if (i == pivot) continue;
        long long currentDiff = abs(calculateTorque(i));
        if (addPos < i) currentDiff += abs((i - addPos) * newWeight);
        else currentDiff += abs((addPos - i) * newWeight);

        if (currentDiff < minDiff) {
            minDiff = currentDiff;
            bestPos = i;
        }
    }

    cout << bestPos << '\n';
    return 0;
}

Tags: competitive-programming algorithm-design cpp graph-traversal dynamic-programming

Posted on Fri, 18 Sep 2026 16:02:06 +0000 by abcdx