暴力深搜居然没超时

P1217 [USACO1.5] 回文质数 Prime Palindromes

Kenny_huang @ 2024-02-01 20:39:33

居然没超时吗,我在题解上看到好多人说暴力会超诶 反正我直接枚举所有数字,然后如果回文且为质数就放到数组里面,然后输出

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

vector<int> v;
int a[10];
int l, r;

bool check(int n) {
    string str = to_string(n);
    for(int i = 0, j = str.size() - 1; i < j; i++, j--) {
        if(str[i] != str[j]) return false;
    }
    return true;
}

bool is_prime(int n) {
    for(int i = 2; i <= n / i; i++) {
        if(n % i == 0) return false;
    }
    return true;
}

void dfs(int u) {
    if(u == 8) {
        int ans = 0, temp = 1000000;
        for(int i = 1; i <= 7; i++) {
            ans += a[i] * temp;
            temp /= 10;
        }
        // cout << ans << endl;
        if(ans >= l && ans <= r) {
            if(check(ans) && is_prime(ans)) {
                v.push_back(ans);
            }
        }
        return ;
    }
    for(int i = 0; i <= 9; i++) {
        a[u] = i;
        dfs(u + 1);
    }
}

int main() {
    cin >> l >> r;
    dfs(1);
    for(int i = 0; i < v.size(); i++) cout << v[i] << endl;
    return 0;
}

by Cuimenghao @ 2024-02-07 12:04:39


by jiangzhiaan @ 2024-11-02 19:23:11

666


|