最短零一串
题目要求
给定一个数字,求出这个数字乘以一个正整数所能得到的最短零一串。若不存在则输出"Not Found"
来源
记不清了 原题并非如此直接。
输入
一个数字n
输出
n的最短另一串。若不存在,输出 “Not Found”
思路
广度优先搜索,以结果中的每一位数码为单位一个状态。
原理是当在末尾加入一个新的数码时,其mod值将会符合以下条件:
//如果数码为0,则新的值为
cur.mod * 10 % n
//如果数码为1,则新的值为
(cur.mod * 10 + 1) % n
同时,为了优化以及排除not found的情况,可以注意到:
每两个同余的数事实上只需要保存较短的一个,因此采用数组thru记录了余数是否出现。
如果都出现过而尚未发现答案,则失败;
若再次出现,则不再放入bfs队列中。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
struct stat{
int bit;
int prev;
int mod;
stat(int b, int p, int m){
bit = b;
prev = p;
mod = m;
}
};
int main(){
int n;
cin >> n;
bool thru[n];
memset(thru, false, sizeof(thru));
queue<stat> q;
vector<stat> trace;
q.push(stat(1, -1, 1 % n));
thru[1] = 0;
stat cur = q.front();
while (!q.empty()){
cur = q.front();
if (cur.mod == 0) break;
trace.push_back(cur);
int p = (int)trace.size() - 1;
if (!thru[cur.mod * 10 % n]) q.push(stat(0, p, cur.mod * 10 % n)), thru[cur.mod * 10 % n] = true;
if (!thru[(cur.mod * 10 + 1) % n]) q.push(stat(1, p, (cur.mod * 10 + 1) % n)), thru[(cur.mod * 10 + 1) % n] = true;
q.pop();
}
if (cur.mod != 0){
cout << "Not Found" << endl;
return 0;
}
vector<int> res;
res.push_back(cur.bit);
while (cur.prev != -1){
cur = trace[cur.prev];
res.push_back(cur.bit);
}
for (int i = (int)res.size() - 1; i >= 0; i--){
cout << res[i];
}
cout << endl;
return 0;
}