Loading

Find The Multiple || 一维bfs ?

 

 

一维bfs瞎起的就随便说说,主要是平常bfs求最短路感觉常见简单的都是二维起步,然后今天发现其实bfs做普通边权为1的最短路小题非常的好用~

首先就是怎么不重不漏枚举所有情况呢,就可以比如第一个数是1,第二个数就有两种选择:1 * 10和1 * 10 + 1,其实就是不漏了,非常的巧妙(明显)。

 1 #include <iostream>
 2 #include <queue>
 3 #include <cstring>
 4 #include <algorithm>
 5 //#include <array>
 6 #define gogo ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
 7 using namespace std;
 8 //using i64 = long long;
 9 //#define endl '\n';
10 const string YES = "Yes";
11 const string NO = "No";
12 int n;
13 
14 long long bfs(int x) {
15     queue<long long> q;
16     q.push(1);
17 
18     while (q.size()) {
19         long long t = q.front();
20         q.pop();
21 
22         if (t % n == 0) 
23             return t;
24         q.push(t * 10);
25         q.push(t * 10 + 1);
26     }
27     return -1;
28 }
29 int main() {
30     gogo;
31 
32     while (cin >> n && n) {
33         cout << bfs(n) << '\n';
34     }
35 }
View Code

 

可以多找找这种题的思路,搜索目前还是超级薄弱项。。。

 

posted @ 2023-02-18 22:42  KakaDBL  阅读(25)  评论(0)    收藏  举报