点击打开链接
Pile twhere t is the number of the test case (starting at 1). Each of the next m lines should be of the form
Card qi is a face up k.or
Card qi is a face down k.accordingly, for i = 1, .., m, where k is the number of the card.
Card 3 is a face up 4.
5 UUUDD RRLL 5 1 2 3 4 5 10 UUDDUUDDUU LLLRRRLRL 4 3 7 6 1 0
Pile 1 Card 1 is a face down 2. Card 2 is a face up 1. Card 3 is a face up 4. Card 4 is a face down 5. Card 5 is a face up 3. Pile 2 Card 3 is a face down 1. Card 7 is a face down 9. Card 6 is a face up 7. Card 1 is a face down 5.
题意:给你几张牌的朝向(上下),然后在给你一个操作方案:将最左或者最右的牌翻到其后或前的牌堆上,翻的牌的朝向改变。最后给你一组牌在一堆的位置,叫你输出其朝向和牌的值
思路:可以把初始化的每张牌都放在一个栈中,然后通过栈来翻动,很形象的体现了栈的特点。直到都合为一个栈位置(实际上 ,合成一个栈还是可以操作的,只是这里不必了)
package stack; import java.util.Scanner; import java.util.Stack; public class P3328 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=1; while(sc.hasNext()){ int n=sc.nextInt(); if(n==0){ break; } String dirc=sc.next();//输入初始朝向 String operate=sc.next();//输入操作步骤 int m=sc.nextInt(); int[] a=new int[m]; for(int i=0;i<m;i++){ a[i]=sc.nextInt(); } Stack[] stack=new Stack[n];//首先每张牌放入一个栈类中(由于前面的坑,有阴影了,所以这里就直接用java包中的栈类了,但是尽量还是自己写好点) char[] ch=dirc.toCharArray(); Card[] card=new Card[n];//将每个牌放入牌类中,牌有属性:牌的值,和朝向 for(int i=0;i<n;i++){ card[i]=new Card(i+1,ch[i]); stack[i]=new Stack(); stack[i].push(card[i]); } int low=0,high=n-1,i=0; Card c; //R、L表示每次都从最左和最右向中间翻牌,直到都叠在一起(也就是low=high) while(true){ if(low==high){ break; } if(operate.charAt(i++)=='R'){ while(stack[high].isEmpty()!=true){//将当前最右边栈中的所有牌都翻到其前一个栈中 c=(Card)stack[high].pop(); c.changeDir(); stack[high-1].push(c); } high--; }else{ while(stack[low].isEmpty()!=true){//将当前最左边栈中的所有牌都翻到其后一个栈中 c=(Card)stack[low].pop(); c.changeDir(); stack[low+1].push(c); } low++; } //System.out.println(low+"((((((("+high); } i=0; while(stack[low].isEmpty()!=true){//将最后一个栈中的所有牌都放入一个牌数组中,因为结果要求按所给的数a[i](也就是在栈中的位置),输出第a[i]张牌的情况 card[i++]=(Card) stack[low].pop(); //System.out.println("value="+c.value+" dir="+c.dir); } System.out.println("Pile "+t); t++; for(int j=0;j<m;j++){ System.out.println("Card "+a[j]+" is a face "+card[a[j]-1].dir+" "+card[a[j]-1].value+"."); } } } } class Card{ int value; String dir; public Card(int value,char dir){ this.value=value; if(dir=='U'){ this.dir="up"; }else{ this.dir="down"; } } public void changeDir(){ if(this.dir=="up"){ this.dir="down"; }else{ this.dir="up"; } } }