Algorithm Implementation Challenges and Solutions

Exponential Calculation

This solution calculates the power of 2 for a given non-negative integer n. Instead of iterating, we utilize bit shifting for efficiency.

#include <iostream>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int exponent;
    std::cin >> exponent;
    
    long long result = 1LL << exponent;
    std::cout << "2^" << exponent << " = " << result << "\n";
    
    return 0;
}

Celsius Temperature Conversion

Converts a fixed Fahrenheit value (100) to Celsius using the standard conversion formula.

#include <iostream>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    const int fahr = 100;
    double celsius = 5.0 * (fahr - 32) / 9.0;
    
    std::cout << "fahr = " << fahr << ", celsius = " << static_cast<int>(celsius) << "\n";
    
    return 0;
}

Chinese Digit Pronunciation

Reads an integer and outputs the Mandarin Chinese pronunciation for each digit. Handles negative numbers by prefixing "fu".

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    const std::vector<std::string> digits = {
        "ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"
    };
    
    std::string input;
    std::cin >> input;
    
    if (input[0] == '-') {
        std::cout << "fu ";
        input.erase(input.begin());
    }
    
    for (size_t i = 0; i < input.size(); ++i) {
        std::cout << digits[input[i] - '0'];
        std::cout << (i == input.size() - 1 ? "\n" : " ");
    }
    
    return 0;
}

Sum of Factorials

Computes the cumulative sum of factorials from 1! to n!. This uses a single pass to update the factorial value and accumulate the sum.

#include <iostream>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    long long limit;
    std::cin >> limit;
    
    long long totalSum = 0;
    long long currentFactorial = 1;
    
    for (long long i = 1; i <= limit; ++i) {
        currentFactorial *= i;
        totalSum += currentFactorial;
    }
    
    std::cout << totalSum << "\n";
    
    return 0;
}

String Compression (The "6" Flipping)

Compresses sequences of the digit '6' based on their length: greater than 9 becomes "27", greater than 3 becomes "9", otherwise remains as is.

#include <iostream>
#include <string>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    std::string text;
    std::getline(std::cin, text);
    
    for (size_t idx = 0; idx < text.size(); ) {
        if (text[idx] == '6') {
            size_t end = idx;
            while (end < text.size() && text[end] == '6') ++end;
            int count = end - idx;
            
            if (count > 9) std::cout << "27";
            else if (count > 3) std::cout << "9";
            else std::cout << text.substr(idx, count);
            
            idx = end;
        } else {
            std::cout << text[idx++];
        }
    }
    
    return 0;
}

Fortune Character Rotation

Reads a grid of characters and determines if its symmetrical after rotating 180 degrees. It also replaces a specific placeholder character with a givenn input character.

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

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    char replacement;
    int dimension;
    std::cin >> replacement >> dimension;
    std::cin.ignore(); // Consume newline
    
    std::vector<std::string> original(dimension);
    std::vector<std::string> rotated(dimension);
    
    for (int i = 0; i < dimension; ++i) {
        std::getline(std::cin, original[i]);
        rotated[i] = original[i];
        std::reverse(rotated[i].begin(), rotated[i].end());
    }
    
    std::reverse(rotated.begin(), rotated.end());
    
    if (original == rotated) {
        std::cout << "bu yong dao le\n";
    }
    
    for (const auto& line : rotated) {
        for (char ch : line) {
            std::cout << (ch == '@' ? replacement : ch);
        }
        std::cout << "\n";
    }
    
    return 0;
}

Natural Language Processing Simulation

A complex simulation of an AI chatbot preprocessing. It handles space normalization, punctuation correction, capitalization (specifically "I"), and phrase replacement ("can you" -> "I can").

#include <iostream>
#include <string>
#include <vector>
#include <cctype>

bool isPunctuation(char c) {
    return !std::isalnum(c);
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int count;
    std::cin >> count;
    std::cin.ignore();
    
    for (int i = 0; i < count; ++i) {
        std::string line;
        std::getline(std::cin, line);
        std::cout << line << "\n";
        
        // Replace ? with !
        for (char& c : line) if (c == '?') c = '!';
        
        // Tokenization
        std::vector<std::string> tokens;
        for (size_t j = 0; j < line.size(); ) {
            if (line[j] == ' ') {
                tokens.push_back(" ");
                while (j < line.size() && line[j] == ' ') ++j;
            } else if (!isPunctuation(line[j])) {
                size_t start = j;
                while (j < line.size() && !std::isspace(line[j]) && !isPunctuation(line[j])) ++j;
                tokens.push_back(line.substr(start, j - start));
            } else {
                tokens.push_back(std::string(1, line[j++]));
            }
        }
        
        // Clean up spaces
        while (!tokens.empty() && tokens.back() == " ") tokens.pop_back();
        for (size_t k = tokens.size() - 1; k > 0; --k) {
            if (isPunctuation(tokens[k][0]) && tokens[k-1] == " ") {
                tokens.erase(tokens.begin() + k - 1);
                k--;
            }
        }
        
        // Case conversion
        for (auto& token : tokens) {
            for (char& c : token) {
                if (c >= 'A' && c < 'Z' && c != 'I') c += 32;
            }
        }
        
        // Phrase replacements
        for (size_t k = 0; k < tokens.size(); ++k) {
            if (tokens[k] == "I" || tokens[k] == "me") {
                tokens[k] = "you#";
            }
        }
        
        for (size_t k = 0; k + 2 < tokens.size(); ++k) {
            std::string phrase = tokens[k] + tokens[k+1] + tokens[k+2];
            if (phrase == "can you" || phrase == "could you") {
                tokens[k] = "I";
                tokens[k+1] = "can";
                tokens[k+2] = ""; // Placeholder to be removed or ignored
                k += 2;
            }
        }
        
        std::cout << "AI: ";
        for (const auto& token : tokens) {
            for (char c : token) {
                if (c != '#') std::cout << c;
            }
        }
        std::cout << "\n";
    }
    return 0;
}

Binary Tree Path Traversal

Determines the leaf node index based on a binary path string ('y' for left, 'n' for right). Effectively converts a binary string to a decimal value.

#include <iostream>
#include <string>
#include <functional>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int depth, queries;
    std::cin >> depth >> queries;
    
    while (queries--) {
        std::string path;
        std::cin >> path;
        
        std::function<int(int)> traverse = [&](int index) {
            if (index >= depth) return 1;
            if (path[index] == 'y') return traverse(index + 1);
            return (1 << (depth - index - 1)) + traverse(index + 1);
        };
        
        std::cout << traverse(0) << "\n";
    }
    return 0;
}

Red Packet Ranking

Calculates net gain from red packets, accounts for the number of packets received, and sorts users accordingly.

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

struct User {
    int id;
    int packetsReceived;
    long long netGain; // stored in cents
};

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int userCount;
    std::cin >> userCount;
    
    std::vector<User> users(userCount + 1);
    for (int i = 1; i <= userCount; ++i) users[i].id = i;
    
    for (int i = 1; i <= userCount; ++i) {
        int count;
        std::cin >> count;
        long long totalDistributed = 0;
        
        for (int j = 0; j < count; ++j) {
            int receiver, amount;
            std::cin >> receiver >> amount;
            
            totalDistributed += amount;
            users[receiver].packetsReceived++;
            users[receiver].netGain += amount;
        }
        users[i].netGain -= totalDistributed;
    }
    
    users.erase(users.begin());
    std::sort(users.begin(), users.end(), [](const User& a, const User& b) {
        if (a.netGain != b.netGain) return a.netGain > b.netGain;
        if (a.packetsReceived != b.packetsReceived) return a.packetsReceived > b.packetsReceived;
        return a.id < b.id;
    });
    
    for (const auto& u : users) {
        std::cout << u.id << " " << std::fixed << std::setprecision(2) << (u.netGain / 100.0) << "\n";
    }
    
    return 0;
}

Red Alert: Connectivity Check

Uses Union-Find to track connected components in a graph. If removing a city increases the number of disconnected components (excluding the removed city), a red alert is triggered.

#include <iostream>
#include <vector>

class DisjointSet {
    std::vector<int> parent;
public:
    DisjointSet(int n) {
        parent.resize(n);
        for (int i = 0; i < n; ++i) parent[i] = i;
    }
    
    int find(int x) {
        return parent[x] == x ? x : parent[x] = find(parent[x]);
    }
    
    void unite(int x, int y) {
        int px = find(x), py = find(y);
        if (px != py) parent[px] = py;
    }
    
    int countComponents(int n) {
        int cnt = 0;
        for (int i = 0; i < n; ++i) if (parent[i] == i) cnt++;
        return cnt;
    }
};

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int cityCount, roadCount;
    std::cin >> cityCount >> roadCount;
    
    std::vector<std::pair<int, int>> roads(roadCount);
    DisjointSet ds(cityCount);
    
    for (int i = 0; i < roadCount; ++i) {
        std::cin >> roads[i].first >> roads[i].second;
        ds.unite(roads[i].first, roads[i].second);
    }
    
    int currentComponents = ds.countComponents(cityCount);
    
    int occupiedCount;
    std::cin >> occupiedCount;
    std::vector<bool> isOccupied(cityCount, false);
    
    while (occupiedCount--) {
        int target;
        std::cin >> target;
        isOccupied[target] = true;
        
        DisjointSet tempDs(cityCount);
        for (const auto& road : roads) {
            if (!isOccupied[road.first] && !isOccupied[road.second]) {
                tempDs.unite(road.first, road.second);
            }
        }
        
        int newComponents = 0;
        for (int i = 0; i < cityCount; ++i) {
            if (!isOccupied[i] && tempDs.find(i) == i) newComponents++;
        }
        
        if (newComponents > currentComponents) {
            std::cout << "Red Alert: City " << target << " is lost!\n";
        } else {
            std::cout << "City " << target << " is lost.\n";
        }
        
        currentComponents = newComponents;
        
        if (std::all_of(isOccupied.begin(), isOccupied.end(), [](bool v){ return v; })) {
            std::cout << "Game Over.\n";
        }
    }
    
    return 0;
}

Seating Arrangement (Friends and Enemies)

Manages relationships using Union-Find for friends and an adjacency matrix for enemies to determine if two people can sit together.

#include <iostream>
#include <vector>

class UnionFind {
    std::vector<int> root;
public:
    UnionFind(int n) { root.resize(n); for(int i=0; i<n; ++i) root[i]=i; }
    int find(int x) { return root[x]==x ? x : root[x]=find(root[x]); }
    void connect(int a, int b) { root[find(a)] = find(b); }
};

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int people, relations, queries;
    std::cin >> people >> relations >> queries;
    
    UnionFind uf(people);
    std::vector<std::vector<int>> enemies(people, std::vector<int>(people, 0));
    
    while (relations--) {
        int a, b, type;
        std::cin >> a >> b >> type;
        if (type == 1) uf.connect(a, b);
        else enemies[a][b] = enemies[b][a] = 1;
    }
    
    while (queries--) {
        int a, b;
        std::cin >> a >> b;
        
        bool sameGroup = uf.find(a) == uf.find(b);
        bool isEnemy = enemies[a][b];
        
        if (!sameGroup && !isEnemy) std::cout << "OK\n";
        else if (sameGroup && !isEnemy) std::cout << "No problem\n";
        else if (sameGroup && isEnemy) std::cout << "OK but...\n";
        else std::cout << "No way\n";
    }
    
    return 0;
}

Binary Search Tree Verification

Verifies if an input array represents the pre-order traversal of a Binary Search Tree or its mirror image. Constructs the tree and compares traversals.

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

struct Node {
    int val;
    std::shared_ptr<Node> left, right;
};

class BST {
public:
    std::shared_ptr<Node> root;
    
    void insert(int value) {
        root = insertRec(root, value);
    }
    
    std::shared_ptr<Node> insertRec(std::shared_ptr<Node> node, int value) {
        if (!node) return std::make_shared<Node>(Node{value, nullptr, nullptr});
        if (value < node->val) node->left = insertRec(node->left, value);
        else node->right = insertRec(node->right, value);
        return node;
    }
    
    void getPreAndPost(std::vector<int>& pre, std::vector<int>& post, bool mirrored) {
        traverse(root, pre, post, mirrored);
    }
    
    void traverse(std::shared_ptr<Node> node, std::vector<int>& pre, std::vector<int>& post, bool mirrored) {
        if (!node) return;
        pre.push_back(node->val);
        
        auto first = mirrored ? node->right : node->left;
        auto second = mirrored ? node->left : node->right;
        
        traverse(first, pre, post, mirrored);
        traverse(second, pre, post, mirrored);
        post.push_back(node->val);
    }
};

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int n;
    std::cin >> n;
    std::vector<int> input(n);
    for (auto& x : input) std::cin >> x;
    
    BST tree;
    for (int x : input) tree.insert(x);
    
    std::vector<int> pre, post;
    tree.getPreAndPost(pre, post, false);
    
    if (pre == input) {
        std::cout << "YES\n";
        for (size_t i = 0; i < post.size(); ++i) 
            std::cout << post[i] << (i == post.size() - 1 ? "\n" : " ");
        return 0;
    }
    
    pre.clear(); post.clear();
    tree.getPreAndPost(pre, post, true);
    
    if (pre == input) {
        std::cout << "YES\n";
        for (size_t i = 0; i < post.size(); ++i) 
            std::cout << post[i] << (i == post.size() - 1 ? "\n" : " ");
    } else {
        std::cout << "NO\n";
    }
    
    return 0;
}

Tags: C++ algorithms Data Structures graph theory String Manipulation

Posted on Thu, 25 Jun 2026 17:46:32 +0000 by TheBrandon