返回首页 C++ 模板

模拟算法模板

按题目描述的步骤逐步执行——忠实还原过程

模拟 过程还原 日期 闰年 GESP3
#include <bits/stdc++.h>
using namespace std;

int main() {
    // ====== 1. 日期推算 ======
    int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    auto isLeap = [](int y) { return (y%4==0 && y%100!=0) || y%400==0; };

    int year = 2024, month = 1, day = 1;
    int n = 100;  // 100天后
    while (n--) {
        day++;
        int maxDay = daysInMonth[month];
        if (month == 2 && isLeap(year)) maxDay = 29;
        if (day > maxDay) { day = 1; month++; }
        if (month > 12) { month = 1; year++; }
    }
    cout << year << "-" << month << "-" << day << endl;

    // ====== 2. 进制转换模拟 ======
    // 十进制转二进制(短除法)
    int num = 13;
    string bin;
    while (num > 0) {
        bin = char('0' + num % 2) + bin;
        num /= 2;
    }
    cout << bin << endl;  // 1101

    // ====== 3. 约瑟夫问题模拟 ======
    int total = 10, step = 3;
    queue<int> q;
    for (int i = 1; i <= total; i++) q.push(i);
    int cnt = 0;
    while (q.size() > 1) {
        cnt++;
        int cur = q.front(); q.pop();
        if (cnt % step == 0) continue;  // 出列
        q.push(cur);
    }
    cout << q.front() << endl;  // 最后剩下的人

    return 0;
}

📖 要点说明

⚠️ 常见错误