Description
KEY Inc., the leading company in security hardware, has developed a new kind of safe. To unlock it, you don't need a key but you are required to enter the correct n-digit code on a keypad (as if this were something new!). There are several models available, from toy safes for children (with a 2-digit code) to the military version (with a 6-digit code).Input
The input contains several test cases. Every test case is specified by an integer n. You may assume that 1<=n<=6. The last test case is followed by a zero.Output
For each test case specified by n output a line containing a sequence of 10n + n - 1 digits that contains each n-digit sequence exactly once.Sample Input
1 2 0
Sample Output
0123456789 00102030405060708091121314151617181922324252627282933435363738394454647484955657585966768697787988990
題意:破解一套1-6位長度密碼的系統,尋找這樣一個序列:對於N位的密碼10^N+N-1長度的連續的長為N的串能夠枚舉完所有的密碼。
思路:做的頭疼,懶得寫了。就拿別人的題解吧:對於每一個長度為n的串,讓該串的前n-1位為一個節點,後n-1位為另一個節點這樣就確定了這個串。
n 位數有10n 種編碼方案(即10n 組數),要使得一個數字序列包含這10n 組n 位數,且序列的長
度最短,唯一的可能是每組數出現一次且僅一次、且前一組數的後n-1 位是後一組數的前n-1 位,
這樣10n 組數各取1 位,共10n 位,再加上最後一組數的後n-1 位,總位數是10n + n - 1。
#include#include #include #include using namespace std; const int maxn = 1000015; struct Edge { int v, next; } e[maxn]; int n, mod, head[maxn], stk[maxn]; int idx, lim, edge, top; char vis[maxn]; void insert(int a, int b) { e[idx].v = b; e[idx].next = head[a]; head[a] = idx++; } void dfs() { stk[top++] = 0; while (1) { int flag = 0; int v = stk[top-1]; if (top >= idx-(n-2)) return; for (int i = head[v]; i != -1; i = e[i].next) if (!vis[i]) { flag = 1; vis[i] = 1; stk[top++] = e[i].v; break; } if (!flag) --top; } } int main() { while (scanf("%d", &n) != EOF && n) { if (n == 1) { printf("0123456789\n"); continue; } idx = top = 0; memset(head, -1, sizeof(head)); memset(vis, 0, sizeof(vis)); lim = 1; for (int i = 1; i < n; i++) lim *= 10; edge = lim * 10; mod = lim / 10; for (int i = 0; i < lim; i++) for (int j = 9; j >= 0; j--) insert(i, (i%mod)*10+j); dfs(); for (int i = 0; i < top-1; i++) printf("%d", stk[i]/mod); printf("%d", stk[top-1]); for (int i = 1; i < n; i++) printf("0"); printf("\n"); } return 0; }