P5440 【XR-2】奇迹 ( dfs

#include 
using namespace std;
typedef long long ll;
typedef pair PII;
typedef pair PDD;
typedef unsigned long long ull;
int t;
int a[10];
int res;
int month[] ={0,31,28,31,30,31,30,31,31,30,31,30,31};
int prime[1240];
bool prim2(int n){
    if(n == 1) return false;
    if(n == 2 || n == 3) return true;
    if(n % 6 != 1 && n % 6 != 5) return false;
    for(int i=5;i*i<=n;i+=6){
        if(n % i == 0 || n % (i+2) == 0)return false;
    }
    return true;
}
bool checkdate(int n){
    int day = n % 100;
    int mon = n % 10000 / 100;
    int year = n /10000;
    if(year < 1 || year > 9999 )return false;
    if(mon < 1 ||  mon >12) return false;
    if(mon == 2){
        if(day == 29 && ((year % 4 == 0) && (year % 100 != 0) ||  year % 400 == 0)){
            return true;
        }
    }

    if(day >= 1 && day <= month[mon]){
            return true;
    }
    return false;
}

bool checkprim(int n){
    int day = n % 100;
    int md = n % 10000;
    if(prime[day] == 1 && prime[md] == 1 && prim2(n)){
        return true;
    }
    return false;
}

void dfs(int x,int n){
    if(x > 8) {
        if(checkdate(n) && checkprim(n)){
            res++;
        }
        return;
    }

    if(a[x] == -1){
        for(int i=0;i<=9;i++){
            int u = n * 10 + i;
            dfs(x+1,u);
        }
    }else{
        dfs(x+1,n*10+a[x]);
    }

}

int main() {
    for(int i=2;i<=1240;i++){
        if(prime[i] == 0){
            prime[i] = 1;
            for(int j=i+i;j<=1240;j+=i){
                prime[j] = -1;
            }
        }
    }
    cin>>t;
    while(t--){
        int flag = 0;
        res = 0;
        a[0] = 0;
        for(int i=1;i<=8;i++){
            char c;
            cin>>c;
            if(c == '-')a[i] = -1 , flag ++;
            else a[i] = c - '0';
        }
        if(flag == 8){
            cout<<55157<

神奇的判断 全是--------的情况的优化

判断日期

你可能感兴趣的:(搜索,深度优先,算法,图论)