POJ 1208 The Blocks Problem (UVA 101)
2012-07-11 16:56
405 查看
题意:n堆木块,每堆一个,编号0到n-1,现在给你一些操作指令,分别是:
move a onto b:将a,b之上的木块复位,再将a放到b上;
move a over b:将a之上的木块复位,再将a放到包含b的堆的堆顶;
pile a onto b:将b之上的木块复位,再将a及a之上的木块放到b上;
pile a over b:将a及a以上的木块放到包含b的堆的堆顶。
输出最后的状态即可。
解题思路:用数组模拟即可,要注意的的是:当a=b是,不用操作;当a与b在同一堆中,该操作属于错误指令,直接忽略。还有,可以证明,将某个木块上的其他木块复位时,不用担心原来的位置被其他木块占了。
Memory: 692K Time: 0MS #include <iostream> #include <stdio.h> #include <string.h> using namespace std; int s[30][30],sn[30],n,a,b;//堆,堆中木块数,总堆数 char op[5],dr[5]; void init()//初始化 { for(int i=0;i<n;i++) { sn[i]=1; s[i][1]=i; } } int find(int x)//找到标号为x的木块所在的堆 { for(int i=0;i<n;i++) for(int j=1;j<=sn[i];j++) { if(s[i][j]==x) return i; } } void reset(int x)//将木块x之上的木块复位 { int i=find(x); for(int j=1;j<=sn[i];j++) { if(s[i][j]==x) { int p=j+1; for(;p<=sn[i];p++) { int y=s[i][p]; s[y][1]=y; sn[y]=1; } sn[i]=j; break; } } } void print()//输出所有堆状态 { for(int i=0;i<n;i++) { printf("%d:",i); for(int j=1;j<=sn[i];j++) { printf(" %d",s[i][j]); } printf("\n"); } } int main() { // freopen("in.txt","r",stdin); while(scanf("%d",&n)!=EOF) { int x,y; init(); while(scanf("%s",op)) { if(!strcmp(op,"quit")) break; scanf("%d%s%d",&a,dr,&b); if(a==b) continue; if(!strcmp(op,"move") && !strcmp(dr,"onto")) { x=find(a); y=find(b); if(x==y) continue;//如果a,b在同一堆,则操作忽略,下同 reset(a); reset(b); sn[y]++; s[y][sn[y]]=a; sn[x]--; } else if(!strcmp(op,"move") && !strcmp(dr,"over")) { x=find(a); y=find(b); if(x==y) continue; reset(a); sn[y]++; s[y][sn[y]]=a; sn[x]--; } else if(!strcmp(op,"pile") && !strcmp(dr,"onto")) { y=find(b); x=find(a); if(x==y) continue; reset(b); for(int i=1;i<=sn[x];i++) { if(s[x][i]==a) { int tmp=sn[x]; sn[x]=i-1; for(int j=i;j<=tmp;j++) { sn[y]++; s[y][sn[y]]=s[x][j]; } break; } } } else if(!strcmp(op,"pile") && !strcmp(dr,"over")) { x=find(a); y=find(b); if(x==y) continue; for(int i=1;i<=sn[x];i++) { if(s[x][i]==a) { int tmp=sn[x]; sn[x]=i-1; for(int j=i;j<=tmp;j++) { sn[y]++; s[y][sn[y]]=s[x][j]; } break; } } } } print(); } return 0; }
相关文章推荐
- uva 101 POJ 1208 The Blocks Problem 木块问题 vector模拟
- uva 101 POJ 1208 The Blocks Problem 木块问题 vector模拟
- UVa 101: The Blocks Problem
- uva101 - The Blocks Problem
- POJ-1208-The Blocks Problem
- UVa101 - The Blocks Problem
- uva 101 - The Blocks Problem
- UVA101-The Blocks Problem
- Uva 101 - The Blocks Problem
- uva 101 The Blocks Problem
- uva 101 The Blocks Problem(模拟)
- 【例题5-2 UVA - 101】The Blocks Problem
- UVa 101 - The Blocks Problem
- uva 101 The Blocks Problem
- UVa 101 The Blocks Problem 【STL】【vector】【模拟】
- uva 101 The Blocks Problem
- UVA101- The Blocks Problem
- POJ 1208 The Blocks Problem
- uva 101 木块问题 The Blocks Problem
- uva 101 - The Blocks Problem