#include <stdio.h>
#include <stdlib.h>

struct disk {
    int num;
    struct disk *next;
};

struct rods {
    int ndisks;
    int from;
    int via;
    int to;
};

int continuos_count_rod(const struct disk *d) {
    int count;
    for (count = 0; d && d->num == count + 1; d = d->next)
        count++;
    return count;
}

void put_disk(struct disk **d, int num) {
    struct disk *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->num = num;
    tmp->next = *d;
    *d = tmp;
}

void move_disk(struct disk **src, struct disk **dst) {
    struct disk *tmp;
    tmp = *src;
    *src = (*src)->next;
    tmp->next = *dst;
    *dst = tmp;
}

void swap(int *x, int *y) {
    int tmp = *x;
    *x = *y;
    *y = tmp;
}

void from_smallest(struct rods *r, struct disk *disks[]) {
    if (disks[r->to] && disks[r->to]->num == 1)
            swap(&r->from, &r->to);
    else if (disks[r->via] && disks[r->via]->num == 1)
            swap(&r->from, &r->via);
}

void not_smallest_to_from(struct rods *r, struct disk *disks[]) {
    if (disks[r->from] && disks[r->from]->num == 1)
        swap(&r->from, &r->via);
    else if (disks[r->to] && disks[r->to]->num == 1)
        swap(&r->to, &r->via);
}

void decide_subtower(struct rods *r, struct disk *disks[]) {
    if (disks[r->from]) {
        int count = continuos_count_rod(disks[r->from]);
        for (int i = count; i > 1; i--)
            swap(&r->via, &r->to);
    }
}

void solve(struct rods *r) {
    struct disk *disks[] = {NULL, NULL, NULL, NULL};
    for (int i = r->ndisks; i > 0; i--)
        put_disk(&disks[r->from], i);
    for (int i = 1; (disks[1] || disks[2]);) {
        if (i % 2 == 1)
            from_smallest(r, disks);
        else
            not_smallest_to_from(r, disks);
        decide_subtower(r, disks);
        if (disks[r->from] &&
                (!disks[r->to] ||
                 (disks[r->from]->num < disks[r->to]->num))) {
            move_disk(&disks[r->from], &disks[r->to]);
            printf("%d\t%d: %d -> %d\n",
                    i, disks[r->to]->num, r->from, r->to);
            i++;
        } else
            swap(&r->to, &r->from);
    }
}

int main(int argc, char *argv[]) {
    int ndisks;
    if (argc < 2) {
        fprintf(stderr, "Usage: ./prog <number of disks>\n");
        return 1;
    }
    ndisks = atoi(argv[1]);
    if (ndisks < 1) {
        fprintf(stderr, "Enter a valid number of disks\n");
        return 2;
    }
    struct rods r = {ndisks, 1, 2, 3};
    solve(&r);
    return 0;
}
