題目:ide
給定n個A和2n個B。用這些字符拼成一個字符串。要求這個串的所有前綴和後綴B的個數始終很多於A。post
(一個字符串的前綴是僅僅從開頭到某個位置爲止的子串,後綴是僅僅從某個位置到結尾的子串)。spa
輸入格式code
多組數據。每組數據僅僅有一行,包括一個正整數n。blog
(n<=10^17)。ip
輸出格式內存
每組數據輸出一行,終於結果對99991取餘數的結果。字符串
分析:get
簡單的想法是創建一個二叉樹。深度遍歷一下就能夠。it
但是效率過低,對照較大的n不太適用,臨時沒想到什麼好辦法。先簡單的作作看。
代碼:
<span style="font-size:18px;">#include <stdio.h> #include <stdlib.h> struct Node { int value; struct Node *left; struct Node *right; }; #define n 3 static int result = 0; static int index = 0; static int array[3 * n] = {0}; struct Node* initNode() { struct Node* temp = (struct Node *)malloc(sizeof(struct Node)); temp->value = 0; temp->left = NULL; temp->right = NULL; return temp; } void creatTree(struct Node* parent, int a, int b) { if (a > 0) { struct Node* left = initNode(); left->value = -1; parent->left = left; creatTree(left, a - 1, b); } if (b > 0) { struct Node* right = initNode(); right->value = 1; parent->right = right; creatTree(right, a, b - 1); } if (a <= 0 && b <=0) { return; } } //static int array[100] = {0}; void dfs(struct Node* root, int sum) { int i = 0; if (root == NULL) { //result++; return; } if (root->value == 1 && root->left == NULL && root->right == NULL) { result++; printf("%d\n", root->value); printf("\nget one\n"); return; } sum += root->value; if (sum < 0 || sum > n) { return; } else { printf("%d\n", root->value); //index = 0; dfs(root->left, sum); dfs(root->right, sum); } } void freeNode(struct Node* root) { if (root != NULL) { //printf("%d\n", root->value); //printf("%d\n", root->left->value); freeNode(root->left); freeNode(root->right); free(root); } return; } int main() { int a = 0, b = 0, sum = 0; a = n; b = n * 2; /* 根節點 B */ struct Node *root = initNode(); root->value = 1; /* 創建二叉樹 */ creatTree(root, a, b-1); /* 深度搜索遍歷法獲得結果 */ dfs(root, sum); printf("result = %d\n", result); /* 釋放內存 */ freeNode(root); return 0; } </span>