UVa 101 - The Blocks Problem|java实现

来源:互联网 发布:淘宝店铺广告短信 编辑:程序博客网 时间:2024/06/18 12:56

题目:给你n个方块,有四种操作:

            1.move a onto b,把a和b上面的方块都放回原来位置,然后把a放到b上面;

            2.move a over b,把a上面的放回原处,然后把a放在b所在的方块堆的上面;

            3.pile a onto b,把b上面的放回原来位置,然后把a和a上面的方块整体放到b上面;

            4.pile a over b,把a和a上面的方块整体放到b所在堆的上面。

分析:模拟,数据结构。观察操作,如果是move就是先把a上面的还原,如果是onto就是先把b上面的还原。

            然后,就是移动一堆到另一堆的上面(单个也认为是一堆)。所以设置两个基础操作:

            1.将a上面的还原init_place(a);

            2.将a和上面的(可以没有上面的)放到b上面pile_a_to_b(a,b)。

            那么上述的四组操作就变成下面了:

            1.move a onto b,init_place(a);init_place(b);pile_a_to_b(a,b);

            2.move a over b,init_place(a);pile_a_to_b(a,b);

            3.pile a onto b,init_place(b);pile_a_to_b(a,b);

            4.pile a over b,pile_a_to_b(a,b)。

            利用两个操作轻松解决。具体实现时设置一个place数组记录每个编号的方块对应的堆。

注意:如果a和b已经在一堆中就不要操作,此时认为不用移动,否则会WA。


import java.io.IOException;import java.util.Scanner;public class Test {static int total = 25;//输入的木块总数,不能大于25块static int[] place = new int[25];//储存每个木块的位置,就是在哪一堆  static int[][] stack = new int[25][25];//存储每个位置的所有木块  static int[] top = new int[25]; //存储每个位置的长度public static void init_place(int a){int tmp;//把a上面的木块放回原来的位置while(stack[place[a]][top[place[a]]] != a){//获取a所在堆的最上面一个木块,直到最上面是a为止tmp = stack[place[a]][top[place[a]]];place[tmp] = tmp;//将这个木块的位置,设为跟自己同数目的placetop[tmp]++;//跟自己同数目的高度(top)加一stack[tmp][top[tmp]] = tmp;//将木块存入新位置top[place[a]]--;//原位置的高度减一}}static void pile_a_to_b(int a,int b){int tmp;//把a上面的木块放到b上面while(stack[place[a]][top[place[a]]] != a){//获取a所在堆的最上面一个木块,直到最上面是a为止tmp = stack[place[a]][top[place[a]]];place[tmp] = place[b];//将这个木块的位置,设为b所在位置top[place[b]]++;//b所在位置的堆高度加一stack[place[b]][top[place[b]]] = tmp;//将木块存入新位置top[place[a]]--;//原位置的高度减一}//把a放在b上top[place[b]]++;//b所在位置高度加一stack[place[b]][top[place[b]]] = stack[place[a]][top[place[a]]];//把a放入b所在堆top[place[a]]--;//a原位置高度减一place[a] = place[b];//a的新位置,就是b的位置}public static void main(String[] args) throws IOException {Test test = new Test(); Scanner s = new Scanner(System.in);//输入类do{System.out.println("输入木块数目:");test.total = s.nextInt();//System.out.println(total);//初始化数据for(int i=0;i<test.total;i++){top[i] = 1;//初始化,每个位置只有一块stack[i][0] = i;//每个位置的最低下,放一块}String oper = "m";//m表示move,p表示pileString type = "n";//n表示onto,v表示overdo{oper = s.nextLine();oper = s.nextLine();int a = s.nextInt();type = s.nextLine();type = s.nextLine();int b = s.nextInt();System.out.println(a+oper+type+b);if(place[a] == place[b]){//如果在同一位置(堆),不操作//System.out.println("a,b在同一堆");continue;}int tmp;if(oper.equals("m")){if(type.equals("n")){//把a上面的木块放回原来的位置init_place(a);//把b上面的木块放回原来的位置init_place(b);//把a放在b上pile_a_to_b(a,b);}else{//把a上面的木块放回原来的位置init_place(a);//把a放在b上pile_a_to_b(a,b);}}else{if(type.equals("n")){//把b上面的木块放回原来的位置init_place(b);//把a上面的木块和a都放到b上面pile_a_to_b(a,b);}else{//把a上面的木块和a都放到b上面pile_a_to_b(a,b);}}}while(oper.equals("q"));//q表示结束输入}while(total>0 && total<26);}}



0 0
原创粉丝点击