大三寒假学习进度笔记21

今天看到了一道蓝桥杯的题目,其中使用到了dfs算法,在之前的数据结构中学习过这种算法,但是并没有在代码中使用过,因此根据给出的思路在写了一遍这个题目。
#include<bits/stdc++.h>
using namespace std;

int a[100],ans=0;
bool vis[20240000];
bool check(int date){
    if(vis[date]){
        return false;
    }
    vis[date]=1;
    int mm=date/100%100;
    int dd=date%100;
    if(mm<1||mm>12){
        return false;
    } 
    if(mm==1||mm==3||mm==5||mm==7||mm==8||mm==10||mm==12){
        if(dd>=1&&dd<=31){
            return true;
        }
    }else if(mm==2){
        if(dd>=1&&dd<=28){
            return true;
        }
    }else if(1<=dd&&dd<=30){
        return true;
    }else{
        return false;
    }
}

void dfs(int x,int pos,int date){
    if(x==100) return;
    if(pos == 8){
        if(check(date)) ++ans;
        return;
    }
    if(
    (pos==0 && a[x]==2) ||
    (pos==1 && a[x]==0) ||
    (pos==2 && a[x]==2) ||
    (pos==3 && a[x]==3) ||
    (pos==4 && 0<=a[x] && a[x]<=1) ||
    (pos==5 && 0<=a[x] && a[x]<=9) ||
    (pos==6 && 0<=a[x] && a[x]<=3) ||
    (pos==7 && 0<=a[x] && a[x]<=9) 
    ){
        dfs(x+1,pos+1,date*10+a[x]);
    }
    dfs(x+1,pos,date);
}

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    for(int i=0;i<100;i++){
        cin>>a[i];
    }
    dfs(0,0,0);
    cout<<ans;
    return 0;
} 

其中还使用到了这个函数

ios::sync_with_stdio(0);cin.tie(0);

这个函数是一个“是否兼容stdio”的开关,C++为了兼容C,保证程序在使用了std::printfstd::cout的时候不发生混乱,将输出流绑到了一起。
cincout之所以效率低,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而这段语句可以来打消iostream的输入输出缓存,可以节省许多时间,使效率与scanf与printf相差无几.
posted @ 2024-01-30 22:05  wrf12  阅读(8)  评论(0)    收藏  举报