当前位置:网站首页>[depth first search] Ji suanke: find numbers

[depth first search] Ji suanke: find numbers

2022-07-06 18:46:00 muse_ age

dfs(num) The current number is num

The first is 1, Then everyone can choose 0 perhaps 1.

DFS(num *10);// choice 0 after num

DFS(num*10+1);// choice 1 after num

Because the question in the question is whether it exists , Then we can stop searching after finding a solution .

Pruning operation :

Define a bool Global variables flag, When a solution is found ,flag Set up true,

prune :

if(flag){return;}

  Code :
Use it carefully long long

#include<iostream>
using namespace std;
int n;
bool flag;
void dfs(long long num){
	if(flag==true){
		return;
	}
	if(num%n==0){
		cout<<num<<endl;
		flag=true;
		return;
	}
	
	dfs(num*10);
	dfs(num*10+1);
} 

int main(){
	flag=false;
	cin>>n;
	dfs(1);
}

原网站

版权声明
本文为[muse_ age]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131254418199.html