#include <cstdio> #include <vector> #include <algorithm> using namespace std; #define FOR(i,a,b) for(int (i)=(int)(a); (i)!=(int)(b); ++(i)) struct Node { int id; Node *next_1, *next_2; Node(Node *n1 = 0, Node *n2 = 0):id(-1),next_1(n1),next_2(n2){} }; int n, m; vector<int> L(100, -1), R(100, -1); void set_id(Node *node, int ¤t) { if (node->id != -1) return; node->id = current; ++current; if (node->next_1 != 0) { set_id(node->next_1, current); L[node->id] = node->next_1->id; } if (node->next_2 != 0) { set_id(node->next_2, current); R[node->id] = node->next_2->id; } } int main() { scanf("%d", &n); if (n == 1) { printf("2\n"); printf("2 -1\n"); printf("-1 -1\n"); return 0; } vector<int> P; while (n>0) { P.push_back(n%2); n /= 2; } reverse(P.begin(), P.end()); m = 1; Node *first = new Node(); Node *last = first; FOR(i,1,P.size()) { Node *y = new Node(); Node *x = new Node(y); last->next_1 = x; last->next_2 = y; last = y; m += 2; if (P[i] == 1) { first = new Node(first, x); ++m; } } int current = 1; last->id = m; set_id(first, current); printf("%d\n", m); FOR(i,0,m) printf("%d %d\n", L[i+1], R[i+1]); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #include <cstdio> #include <vector> #include <algorithm> using namespace std; #define FOR(i,a,b) for(int (i)=(int)(a); (i)!=(int)(b); ++(i)) struct Node { int id; Node *next_1, *next_2; Node(Node *n1 = 0, Node *n2 = 0):id(-1),next_1(n1),next_2(n2){} }; int n, m; vector<int> L(100, -1), R(100, -1); void set_id(Node *node, int ¤t) { if (node->id != -1) return; node->id = current; ++current; if (node->next_1 != 0) { set_id(node->next_1, current); L[node->id] = node->next_1->id; } if (node->next_2 != 0) { set_id(node->next_2, current); R[node->id] = node->next_2->id; } } int main() { scanf("%d", &n); if (n == 1) { printf("2\n"); printf("2 -1\n"); printf("-1 -1\n"); return 0; } vector<int> P; while (n>0) { P.push_back(n%2); n /= 2; } reverse(P.begin(), P.end()); m = 1; Node *first = new Node(); Node *last = first; FOR(i,1,P.size()) { Node *y = new Node(); Node *x = new Node(y); last->next_1 = x; last->next_2 = y; last = y; m += 2; if (P[i] == 1) { first = new Node(first, x); ++m; } } int current = 1; last->id = m; set_id(first, current); printf("%d\n", m); FOR(i,0,m) printf("%d %d\n", L[i+1], R[i+1]); } |