题目1 : H国的身份证号码I
描述
H国的身份证号码是一个N位的正整数(首位不能是0)。此外,由于防伪需要,一个N位正整数是合法的身份证号码当且仅当每位数字都小于等于K,并且任意相邻两位数字的乘积也小于等于K。
例如对于K=5, 101、211、210等都是合法的号码,而106、123、421等都是非法的号码。
给定一个正整数N以及K,请从小到大输出所有合法的号码。
输入
两个整数N和K。
对于80%的数据,1 ≤ N ≤ 6。
对于100%的数据,1 ≤ N ≤ 9,1 ≤ K ≤ 5。
输出
按从小到大的顺序输出所有合法的N位号码,每个号码占一行。
2 4样例输出
10 11 12 13 14 20 21 22 30 31 40 41
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<ctype.h>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); }
#define MS(x, y) memset(x, y, sizeof(x))
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b > a)a = b; }
template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b < a)a = b; }
const int N = 0, M = 0, Z = 1e9 + 7, inf = 0x3f3f3f3f;
template <class T1, class T2>inline void gadd(T1 &a, T2 b) { a = (a + b) % Z; }
int casenum, casei;
int n, K;
vector<int>vt;
void dfs(int p, int pre, int now)
{
if (p > n)
{
vt.push_back(now);
return;
}
for (int i = 0; i <= K; ++i)
{
if (i * pre > K)break;
dfs(p + 1, i, now * 10 + i);
}
}
int main()
{
while (~scanf("%d%d", &n, &K))
{
vt.clear();
for (int i = 1; i <= K; ++i)
{
dfs(2, i, i);
}
//sort(vt.begin(), vt.end());
for (auto it : vt)
{
printf("%d\n", it);
}
}
return 0;
}
/*
【题意】
让你判定,对于首位不能为0的恰好n(n <= 9)位数,
如果其每一位的数要<=K 且相邻位的数之乘积<=K,
要你依次输出所有这样的数。
【分析】
直接dfs即可
因为dfs是从小到大贪心dfs的,所以甚至不需要排序。
【时间复杂度&&优化】
O(n)
*/
//输出挂,整数用print,否则用putc,初始化为这里的"PS = PF",最后要输出
char PF[SIZE], *PS = PF, *PT = PF + SIZE;
void putc(char ch)
{
if (PS == PT)fwrite(PF, 1, SIZE, stdout), PS = PF;
*PS++ = ch;
}
template<class T>inline void print(T x)
{
char s[20], *b; b = s;
bool sgn = 0;
if (x < 0) { sgn = 1; x = -x; }
if (!x)*b++ = 48;
while (x) { *b++ = x % 10 + 48; x /= 10; }
if (sgn)putc('-');
while (b-- != s) putc(*b);
}
void prints(char s[])
{
for (int i = 0; s[i]; ++i)putc(s[i]);
}
//这两句话要加在输出之后
fwrite(PF, 1, PS - PF, stdout);
*PS = PF, *PT = PF + SIZE;
//简单输入挂
const int SIZE = 1 << 20;
char S[SIZE], *SS = S, *ST = S, CH;
inline char getc()
{
return SS == ST && (ST = (SS = S) + fread(S, 1, SIZE, stdin), SS == ST) ? 0 : *SS++;
}
template<class T>inline bool read(T &x)
{
x = 0; int sgn = 1;
while (CH = getc(), !isdigit(CH) && CH != '-')if (CH == 0)return 0;
if (CH == '-')sgn = -1; else x = CH ^ 48;
while (CH = getc(), isdigit(CH))x = (x << 3) + (x << 1) + (CH ^ 48);
x *= sgn;
return 1;
}
template<class T1, class T2>inline void read2(T1 &x, T2 &y)
{
read(x); read(y);
}
template<class T1, class T2, class T3>inline void read3(T1 &x, T2 &y, T3 &z)
{
read(x); read(y); read(z);
}