UVA 101 - The Blocks Problem(模拟)

来源:互联网 发布:金融大数据是什么 编辑:程序博客网 时间:2024/06/13 23:06

        题目不难,就是有点麻烦。会用到栈。

#include <stdio.h>#include <string.h>struct _r {    int a[30];    int x;}r[30];int n;// 判断a, b是否在同一堆中int pos(int a) {    for (int i=0; i<n; i++) {        for (int j=0; j<r[i].x; j++) {            if (a == r[i].a[j])                return i;        }    }}int xab(int a) {    for (int i=0; i<n; i++) {        for (int j=0; j<r[i].x; j++) {            if (a == r[i].a[j])                return j;        }    }}void move_onto(int a, int b, int pa, int pb) {    // 下面两个for循环将a, b堆上面的元素返回原来位置    for (int i=r[pa].x-1; r[pa].a[i]!=a; i--) {        r[pa].x--;        r[r[pa].a[i]].x++;    }    for (int i=r[pb].x-1; r[pb].a[i]!=b; i--) {        r[pb].x--;        r[r[pb].a[i]].x++;    }    r[pb].a[r[pb].x] = r[pa].a[r[pa].x-1];    r[pb].x++;    r[pa].x--;}void move_over(int a, int b, int pa, int pb) {    for (int i=r[pa].x-1; r[pa].a[i]!=a; i--) {        r[pa].x--;        r[r[pa].a[i]].x++;    }    r[pb].a[r[pb].x] = r[pa].a[r[pa].x-1];    r[pb].x++;    r[pa].x--;}void pile_onto(int a, int b, int pa, int pb) {    // 将b上面的元素返回原来的位置    for (int i=r[pb].x-1; r[pb].a[i]!=b; i--) {        r[pb].x--;        r[r[pb].a[i]].x++;    }    // 将a上面的元素保持到临时栈中    int tmp_stack[30], top = 0;    do {        r[pa].x--;        tmp_stack[++top] = r[pa].a[r[pa].x];    } while (r[pa].a[r[pa].x] != a);    while (top) {        r[pb].a[r[pb].x] = tmp_stack[top];        top--;        r[pb].x++;    }}void pile_over(int a, int b, int pa, int pb) {    // 将a上面的元素保持到临时栈中    int tmp_stack[30], top = 0;    do {        r[pa].x--;        tmp_stack[++top] = r[pa].a[r[pa].x];    } while (r[pa].a[r[pa].x] != a);    while (top) {        r[pb].a[r[pb].x] = tmp_stack[top];        top--;        r[pb].x++;    }}void print() {    for (int i=0; i<n; i++) {        printf("%d:", i);        for (int j=0; j<r[i].x; j++)            printf(" %d", r[i].a[j]);        printf("\n");    }}int main() {    char str1[6], str2[6];    scanf("%d", &n);    for (int i=0; i<n; i++) {        r[i].x = 1;        r[i].a[0] = i;    }    while (scanf("%s", str1)) {        if (0 == strcmp(str1, "quit"))            break;        int a, b;        scanf("%d%s%d", &a, str2, &b);        int pa, pb;     // a, b所在哪个堆        pa = pos(a); pb = pos(b);        if (pa == pb)            continue;        if (0==strcmp(str1, "move") && 0==strcmp(str2, "onto")) {            move_onto(a, b, pa, pb);        }        if (0==strcmp(str1, "move") && 0==strcmp(str2, "over")) {            move_over(a, b, pa, pb);        }        if (0==strcmp(str1, "pile") && 0==strcmp(str2, "onto")) {            pile_onto(a, b, pa, pb);        }        if (0==strcmp(str1, "pile") && 0==strcmp(str2, "over")) {            pile_over(a, b, pa, pb);        }        //print();    }    print();    return 0;}

 

原创粉丝点击