C plus plus PTA 第二章

由 浪浪猪 发布

函数题



int add(int a, int b) {
    return a + b;
}

double add(double c, double d) {
    return c + d;
}

string add(const string& s1, const string& s2) {
    return s1 + s2;
}
int max(int a, int b, int c=0) {
    int m=a;
    if(b > m) m = b;
    if(c > m)  m = c;
    return m; 
}


编程题

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

bool isPrime(int x) {
    if (x < 2) return false;
    for (int i = 2; i <= sqrt(x); i++) {
        if (x % i == 0) return false;
    }
    return true;
}

void findGoldbachPairs(int x, int y) {
    for (int i = x; i <= y; i += 2) { 
        for (int j = 2; j < i; j++) {
            int k = i - j;

            if (isPrime(j) && isPrime(k)) {

                cout << i << "=" << j << "+" << k << endl;
                break; 
            }
        }
    }
}

int main() {
    int x, y;
    cin >> x >> y;

    findGoldbachPairs(x, y);

    return 0;
}
#include <iostream>
#include <unordered_map>
using namespace std;

string stringify(int a, int b, int c) {
    return to_string(a) + "," + to_string(b) + "," + to_string(c);
}

unordered_map<string, int> memo;

int w(int a, int b, int c) {
    string key = stringify(a, b, c);
    if (memo.find(key) != memo.end()) {
        return memo[key];
    } 

    if (a <= 0 || b <= 0 || c <= 0) {
        return memo[key] = 1;
    }

    if (a > 20 || b > 20 || c > 20) {
        return memo[key] = w(20, 20, 20);
    }

    if (a < b && b < c) {
        return memo[key] = w(a, b, c - 1) + w(a, b - 1, c - 1) - w(a, b - 1, c);
    } else {
        return memo[key] = w(a - 1, b, c) + w(a - 1, b - 1, c) + w(a - 1, b, c - 1) - w(a - 1, b - 1, c - 1);
    }
}

int main() {
    int a, b, c;
    while (true) {
        cin >> a >> b >> c;
        if (a == -1 && b == -1 && c == -1) break;
        cout << "w(" << a << ", " << b << ", " << c << ") = " << w(a, b, c) << endl;
    }

    return 0;
}


收藏

扫描二维码,在手机上阅读

0条评论

发表评论