#include <cstdio> int k; int res[101][2]; int cbits; int bits[31]; int pbits[31]; int cdiv; int div[101]; void divide(int k, int &next) { int v = next; if (k > 2) { res[v][0] = ++next; divide(k / 2 + k % 2, next); res[v][1] = ++next; divide(k / 2, next); } else if (k == 2) { div[cdiv++] = v; div[cdiv++] = v; res[v][0] = res[v][1] = -1; } else { div[cdiv++] = v; res[v][0] = res[v][1] = -1; } } int main() { scanf("%d", &k); cbits = 0; for (int i = 0; i < 31; ++i) { if (k & (1<<i)) { bits[cbits++] = i; } } int n = 1; cdiv = 0; divide(cbits, n); ++n; pbits[bits[cbits - 1]] = n; res[n][0] = res[n][1] = -1; for (int i = 1; i <= bits[cbits - 1]; ++i) { pbits[bits[cbits - 1] - i] = n + 2; res[n][0] = n + 2; res[n][1] = n + 1; res[n + 1][0] = n + 2; res[n + 1][1] = -1; res[n + 2][0] = res[n + 2][1] = -1; n += 2; } for (int i = 0; i < cbits; ++i) { // printf ("X: %d %d | %d\n", bits[i], pbits[bits[i]], div[i]); if (res[div[i]][0] == -1) { res[div[i]][0] = pbits[bits[i]]; } else { res[div[i]][1] = pbits[bits[i]]; } } printf ("%d\n", n); for (int i = 1; i <= n; ++i) { printf("%d %d\n", res[i][0], res[i][1]); } return 0; }
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 64 65 66 67 68 69 70 | #include <cstdio> int k; int res[101][2]; int cbits; int bits[31]; int pbits[31]; int cdiv; int div[101]; void divide(int k, int &next) { int v = next; if (k > 2) { res[v][0] = ++next; divide(k / 2 + k % 2, next); res[v][1] = ++next; divide(k / 2, next); } else if (k == 2) { div[cdiv++] = v; div[cdiv++] = v; res[v][0] = res[v][1] = -1; } else { div[cdiv++] = v; res[v][0] = res[v][1] = -1; } } int main() { scanf("%d", &k); cbits = 0; for (int i = 0; i < 31; ++i) { if (k & (1<<i)) { bits[cbits++] = i; } } int n = 1; cdiv = 0; divide(cbits, n); ++n; pbits[bits[cbits - 1]] = n; res[n][0] = res[n][1] = -1; for (int i = 1; i <= bits[cbits - 1]; ++i) { pbits[bits[cbits - 1] - i] = n + 2; res[n][0] = n + 2; res[n][1] = n + 1; res[n + 1][0] = n + 2; res[n + 1][1] = -1; res[n + 2][0] = res[n + 2][1] = -1; n += 2; } for (int i = 0; i < cbits; ++i) { // printf ("X: %d %d | %d\n", bits[i], pbits[bits[i]], div[i]); if (res[div[i]][0] == -1) { res[div[i]][0] = pbits[bits[i]]; } else { res[div[i]][1] = pbits[bits[i]]; } } printf ("%d\n", n); for (int i = 1; i <= n; ++i) { printf("%d %d\n", res[i][0], res[i][1]); } return 0; } |