Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Competitive Programming Problem Set and Solutions

Tools May 17 1

L1-1: Print Greeting

Print a fixed greeting message.

print("yuan shen, qi dong!")

L1-2: Value Comparison

Given a real number x, compare it to 1 and print the appropriate relational operator.

#include <iostream>
using namespace std;

int main() {
    double val;
    cin >> val;
    
    if(val < 1) cout << '<';
    else if(val > 1) cout << '>';
    else cout << '=';
    
    return 0;
}

L1-3: Expected Learning Calcualtion

Calculate expected learning value based on input parameter n.

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int num;
    cin >> num;
    double result = (num <= 8) ? 2.0 * num : num + 8;
    cout << fixed << setprecision(2) << result / num;
    return 0;
}

L1-4: Custom Multiplier Calculation

Compute a special multiplier value based on input pairs using a custom formula.

#include <iostream>
#include <iomanip>
using namespace std;

double computeMultiplier(double p1, double p2) {
    double base = (p1 + p2) / 2.0;
    if(!p1 || !p2) base /= 2.0;
    if(p1 == 2 && p2 == 2) base *= 2.0;
    return base;
}

int main() {
    double a1, a2, b1, b2;
    cin >> a1 >> a2 >> b1 >> b2;
    double resA = computeMultiplier(a1, a2);
    double resB = computeMultiplier(b1, b2);
    cout << fixed << setprecision(6) << (resA + resB) / 2.0;
    return 0;
}

L1-5: Circuit Coverage Calculation

Calculate minimum power sources needed for circuit coverage given signal strength and positions.

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int main() {
    int n, strength;
    cin >> n >> strength;
    vector<long> x(n), y(n);
    long total = 1;
    
    for(int i = 0; i < n; i++) {
        cin >> x[i] >> y[i];
        if(i) total += abs(x[i] - x[i-1]) + abs(y[i] - y[i-1]);
    }
    
    if(!strength) {
        cout << 0;
        return 0;
    }
    
    int range = (15 - strength) * 2 + 1;
    cout << (total + range - 1) / range;
    return 0;
}

L1-6: String Transformation

Transform input string by replacing specific substrings based on control keywords.

#include <iostream>
#include <string>
using namespace std;

int main() {
    int len;
    string pattern, text;
    cin >> len >> pattern >> text;
    int mainCount = 0, returnCount = 0;
    
    for(int i = 0; i < text.size(); i++) {
        if(text.substr(i, 4) == "main") mainCount++;
        if(text.substr(i, 6) == "return") returnCount++;
        if(text.substr(i, pattern.size()) == pattern && mainCount == returnCount) {
            text[i] = 'z';
            text[i+1] = 'x';
            text[i+2] = 'z';
        }
    }
    
    if(mainCount != returnCount || (!mainCount && !returnCount)) cout << "wrong";
    else cout << text;
    return 0;
}

L1-7: Minimum Difference Partition

Minimize maximum difference by partitioning array into m groups.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<int> arr(n);
    for(int i = 0; i < n; i++) cin >> arr[i];
    
    vector<int> diffs;
    for(int i = 1; i < n; i++) 
        diffs.push_back(arr[i] - arr[i-1]);
    
    sort(diffs.begin(), diffs.end());
    long total = 0;
    for(int i = 0; i <= n - m - 1; i++)
        total += diffs[i];
    
    cout << total;
    return 0;
}

L1-8: Range XOR Query

Answer XOR queries over specified ranges efficiently.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> arr(n+1), prefix(n+1, 0);
    
    for(int i = 1; i <= n; i++) {
        cin >> arr[i];
        prefix[i] = prefix[i-1] ^ arr[i];
    }
    
    int queries;
    cin >> queries;
    while(queries--) {
        int left, right;
        cin >> left >> right;
        cout << (prefix[right] ^ prefix[left-1]) << '\n';
    }
    return 0;
}

L2-1: Factory Simulation

Simulate item processing in a factory using stack operations.

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

int main() {
    int n, k;
    cin >> n >> k;
    vector<int> items(n);
    for(int i = 0; i < n; i++) cin >> items[i];
    
    stack<int> buffer, processor;
    vector<vector<int>> results;
    vector<int> leftovers;
    
    while(!buffer.empty() || !items.empty()) {
        if(!items.empty()) {
            int current = items.back();
            items.pop_back();
            
            if(processor.empty()) {
                processor.push(current);
            }
            else {
                int top = processor.top();
                if(current > top && current - top <= k) {
                    processor.push(current);
                }
                else {
                    if(!buffer.empty()) {
                        int bufTop = buffer.top();
                        if(bufTop > top && bufTop - top <= k) {
                            processor.push(bufTop);
                            buffer.pop();
                        }
                    }
                    buffer.push(current);
                }
            }
        }
        else {
            if(processor.size() >= 2) {
                vector<int> batch;
                while(!processor.empty()) {
                    batch.push_back(processor.top());
                    processor.pop();
                }
                results.push_back(batch);
            }
            else if(processor.size() == 1) {
                leftovers.push_back(processor.top());
                processor.pop();
            }
            
            if(!buffer.empty()) {
                while(!buffer.empty()) {
                    items.push_back(buffer.top());
                    buffer.pop();
                }
                reverse(items.begin(), items.end());
            }
        }
    }
    
    if(processor.size() >= 2) {
        vector<int> finalBatch;
        while(!processor.empty()) {
            finalBatch.push_back(processor.top());
            processor.pop();
        }
        results.push_back(finalBatch);
    }
    else if(processor.size() == 1) {
        leftovers.push_back(processor.top());
    }
    
    for(auto batch : results) {
        for(int item : batch) cout << item << ' ';
        cout << '\n';
    }
    for(int item : leftovers) cout << item << ' ';
    return 0;
}

L2-2: Experience Calculation

Calculate total experience required for fusion operations in a hierarchical structure.

#include <iostream>
#include <vector>
#include <map>
using namespace std;

struct Fusion {
    int target, type, level;
};

int main() {
    int base, operations;
    cin >> base >> operations;
    vector<vector<long>> expTable(4, vector<long>(101, 1));
    expTable[1][1] = expTable[2][1] = expTable[3][1] = 0;
    
    for(int i = 3; i <= 100; i++) {
        expTable[1][i] = expTable[1][i-1] + (i-2);
        expTable[2][i] = expTable[2][i-1] + 2*(i-2);
        expTable[3][i] = expTable[3][i-1] + 5*(i-2);
    }
    
    map<int, vector<Fusion>> fusionMap;
    while(operations--) {
        int result, ingredient, fusionType, fusionLevel;
        cin >> result >> ingredient >> fusionType >> fusionLevel;
        fusionMap[result].push_back({ingredient, fusionType, fusionLevel});
    }
    
    long totalExp = 0;
    auto calculate = [&](auto&& self, int current) -> void {
        for(auto [target, type, level] : fusionMap[current]) {
            self(self, target);
            totalExp += expTable[type][level];
        }
    };
    
    calculate(calculate, base);
    cout << totalExp;
    return 0;
}

L2-3: Lucky Number Pairs

Count pairs of strings that satisfy specific digit sum conditions.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int digitSum(string s) {
    int total = 0;
    for(char c : s) total += c - '0';
    return total;
}

int main() {
    int n;
    cin >> n;
    vector<string> strings(n);
    vector<vector<int>> count(111, vector<int>(2, 0));
    vector<int> sums(n);
    
    for(int i = 0; i < n; i++) {
        cin >> strings[i];
        sums[i] = digitSum(strings[i]);
        count[sums[i]][strings[i].size() % 2]++;
    }
    
    auto process = [&](vector<string>& strList, int flag) {
        long result = 0;
        for(string s : strList) {
            int leftSum = 0;
            for(char c : s) {
                leftSum += c - '0';
                int rightSum = digitSum(s) - leftSum;
                if(rightSum > leftSum) continue;
                result += count[leftSum - rightSum][(s.size() + flag) % 2];
            }
        }
        return result;
    };
    
    long total = process(strings, 0);
    for(string &s : strings) {
        reverse(s.begin(), s.end());
        s.pop_back();
    }
    total += process(strings, 1);
    
    cout << total;
    return 0;
}

L2-4: Priority-Based Collection

Implement a priority-based BFS to maximize collected points on a grid.

#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;

int main() {
    int rows, cols, startX, startY, boosts;
    cin >> rows >> cols >> startX >> startY >> boosts;
    vector<vector<int>> grid(rows+1, vector<int>(cols+1));
    
    for(int i = 1; i <= rows; i++)
        for(int j = 1; j <= cols; j++)
            cin >> grid[i][j];
    
    set<pair<int, int>> boostLocations;
    while(boosts--) {
        int x, y;
        cin >> x >> y;
        boostLocations.insert({x, y});
    }
    
    vector<vector<bool>> visited(rows+1, vector<bool>(cols+1, false));
    priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<>> pq;
    int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
    long totalPoints = 0;
    
    totalPoints += grid[startX][startY];
    grid[startX][startY] = 0;
    visited[startX][startY] = true;
    pq.push({0, {startX, startY}});
    
    while(!pq.empty()) {
        auto [value, pos] = pq.top();
        auto [x, y] = pos;
        pq.pop();
        
        if(value > totalPoints) break;
        totalPoints += value;
        
        for(int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if(nx < 1 || nx > rows || ny < 1 || ny > cols || visited[nx][ny]) continue;
            
            if(boostLocations.count({nx, ny})) {
                totalPoints += grid[nx][ny];
                grid[nx][ny] = 0;
                pq.push({0, {nx, ny}});
                visited[nx][ny] = true;
            }
            else {
                pq.push({grid[nx][ny], {nx, ny}});
                visited[nx][ny] = true;
            }
        }
    }
    
    cout << totalPoints;
    return 0;
}

L3-1: Group Selection Optimization

Maximize value by selecting groups of items with dynamic programming.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int items, groupSize, groups;
    cin >> items >> groupSize >> groups;
    vector<vector<long>> dp(items+1, vector<long>(groups+1, -1));
    vector<long> values(items+1), prefix(items+1, 0);
    dp[0][0] = 0;
    
    for(int i = 1; i <= items; i++) {
        cin >> values[i];
        prefix[i] = prefix[i-1] + values[i];
        dp[i][0] = 0;
    }
    
    for(int i = groupSize; i <= items; i++) {
        for(int j = 1; j <= groups; j++) {
            dp[i][j] = dp[i-1][j];
            if(dp[i-groupSize][j-1] != -1) {
                long groupValue = prefix[i] - prefix[i-groupSize];
                dp[i][j] = max(dp[i][j], dp[i-groupSize][j-1] + groupValue);
            }
        }
    }
    
    cout << dp[items][groups] << '\n';
    vector<pair<int, int>> selections;
    int remaining = groups;
    int position = items;
    
    while(remaining) {
        if(dp[position][remaining] == dp[position-groupSize][remaining-1] + prefix[position] - prefix[position-groupSize]) {
            selections.push_back({position-groupSize+1, position});
            remaining--;
            position -= groupSize;
        }
        else {
            position--;
        }
    }
    
    for(auto [start, end] : selections)
        cout << start << ' ' << end << '\n';
        
    return 0;
}

L3-2: Tree Query Processing

Process tree queries efficiently using DFS order and Fenwick Tree.

#include <iostream>
#include <vector>
using namespace std;

class FenwickTree {
    vector<long> data;
public:
    FenwickTree(int size) : data(size+1, 0) {}
    
    void update(int index, long value) {
        while(index < data.size()) {
            data[index] += value;
            index += index & -index;
        }
    }
    
    long prefixSum(int index) {
        long result = 0;
        while(index > 0) {
            result += data[index];
            index -= index & -index;
        }
        return result;
    }
    
    long rangeQuery(int left, int right) {
        return prefixSum(right) - prefixSum(left-1);
    }
};

int main() {
    int nodes, queries;
    cin >> nodes >> queries;
    vector<long> weights(nodes+1);
    for(int i = 1; i <= nodes; i++) cin >> weights[i];
    
    vector<vector<int>> tree(nodes+1);
    for(int i = 2; i <= nodes; i++) {
        int parent;
        cin >> parent;
        tree[i].push_back(parent);
        tree[parent].push_back(i);
    }
    
    vector<long> startIndex(nodes+1), endIndex(nodes+1);
    vector<int> traversalOrder = {0};
    int counter = 0;
    
    auto dfs = [&](auto&& self, int node, int parent) -> void {
        startIndex[node] = traversalOrder.size();
        traversalOrder.push_back(node);
        for(int neighbor : tree[node]) {
            if(neighbor == parent) continue;
            self(self, neighbor, node);
        }
        endIndex[node] = traversalOrder.size();
        traversalOrder.push_back(node);
    };
    
    dfs(dfs, 1, 0);
    FenwickTree ft(traversalOrder.size());
    
    for(int i = 1; i < traversalOrder.size(); i++) 
        ft.update(i, weights[traversalOrder[i]]);
    
    while(queries--) {
        int type, node;
        long value;
        cin >> type >> node;
        if(type == 1) {
            cin >> value;
            ft.update(startIndex[node], value);
            ft.update(endIndex[node], value);
        }
        else {
            long result = ft.rangeQuery(startIndex[node], endIndex[node]) / 2;
            cout << result << '\n';
        }
    }
    return 0;
}

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.