第5周.翻煎餅

[問題描述](老師已經爲寶寶們翻譯好啦)

Stacks and Queues are often considered the bread andbutter of data structures and find use in architecture, parsing,operating systems, and discrete event simulation.Stacks are also important in thetheory of formal languages.

堆棧和隊列通常被認爲是數據結構的麪包和黃油,可用於體系結構、解析,操作系統和離散事件模擬。堆棧在形式語言理論中也很重要。

 

This problem involves both butter and sustenance inthe form of pancakes rather than bread in addition to a finicky server who flips pancakesaccording to a unique, but complete set of rules.

現在的問題涉及黃油和煎餅(而不是麪包),同時還有一個根據唯一但完整的規則來翻煎餅的服務器。

 

Given a stack of pancakes, you are to write a programthat indicates how the stack can be sorted so that the largest pancake is on the bottom and thesmallest pancake is on the top.

給你一棧的煎餅,請你編寫一個程序用於指示這個棧如何被排序以使得最大的煎餅在最下面而最小的煎餅在最上面。

 

The size of a pancake is given by the pancake’sdiameter.

煎餅的直徑將被給出。

 

All pancakes in a stack have different diameters.

棧中的所有煎餅的直徑都不一樣。

 

Sorting a stack is done by a sequence of pancake“flips”.

對棧排序是通過一系列"翻轉"來完成的。

 

A flip consists of inserting a spatula between twopancakes in a stack and flipping (reversing) all the pancakes on thespatula (reversing the sub-stack).

一次翻轉的意思是:在兩個煎餅之間插入鏟子,然後將鏟子上面的一堆煎餅整體翻過來。也就是指定一個位置,其上的子棧整體翻轉。

 

A flip is specified by giving the position of thepancake on the bottom of the sub-stack to be flipped (relative to the whole stack).

翻轉的位置將會被給出。

 

The pancake on the bottom of the whole stack hasposition 1

and the pancake on the top of a stack of n pancakeshas position n.

位置是這樣定義的:棧底編號爲1,棧頂編號爲n

 

A stack is specified by giving the diameter of eachpancake in the stack in the order in which the pancakes appear.

一個棧的煎餅的給出方式,是從上到下給出煎餅的直徑。

 

For example, consider the three stacks of pancakesbelow (in which pancake 8 is the top-most pancake of the left stack):

舉例來說,這是三個棧,左邊的棧的最上面的煎餅直徑爲8

8 7 2

4 6 5

6 4 8

7 8 4

5 5 6

2 2 7

 

The stack on the left can be transformed to the stackin the middle via flip(3). The middle stack can be transformed into the right stack via the commandflip(1).

左側棧,可在位置3(即直徑7)處翻轉,得到中間的那個棧,而中間那個棧可在位置1(即直徑2)處翻轉,得到右側的棧。

 

Input(輸入)

The input consists of a sequence of stacks ofpancakes. Each stack will consist of between 1 and 30 pancakes and each pancake will have an integerdiameter between 1 and 100. The input is terminated by end-of-file. Each stack is given as a single lineof input with the top pancake on a stack appearing first on a line, the bottom pancake appearing last,and all pancakes separated by a space.

輸入由多個煎餅棧組成。每個棧有1到30個煎餅,每個煎餅的直徑在1-100之間。以文檔結束爲輸入結束。每個棧,獨佔一行,從左到右依次代表從棧頂到棧底的煎餅的直徑,空格隔開。

 

Output(輸出)

For each stack of pancakes, the output should echo theoriginal stack on one line, followed by some sequence of flips that results in the stack ofpancakes being sorted so that the largest diameter pancake is on the bottom and the smallest on top. For eachstack the sequence of flips should be terminated by a ‘0’ (indicating no more flips necessary). Once astack is sorted, no more flips should be made.

對於每個煎餅棧,輸出首先應原樣將棧的數據打印成一行。

隨後的一行是翻轉位置的次序,空格隔開,以0結束。(結束的目標是最大直徑在最下面,最小直徑在最上面)。

 

Sample Input

1 2 3 4 5

5 4 3 2 1

5 1 2 3 4

Sample Output

1 2 3 4 5

0

5 4 3 2 1

1 0

5 1 2 3 4

1 2 0

 

 */

 

解題思路:

在這裏使用java解決問題的,先考慮主要操作,主要操作有兩個:

  • 尋找關鍵點
  • 翻轉

我們定義數組裏邊的最大值和最小值爲關鍵點,找最大最小值就直接遍歷一遍數組,選擇最大最小值;首先對最大值做處理,題目要求需要把最大值放在棧底,在數組中就是數組的最後邊,這裏的最大值位置分兩種情況:

  • 最大值爲數組[0]的位置
  • 最大值在別的位置

 最大值在別的位置時需要先做一次翻轉,把最大值放在數組首位,接下來將位於數組首位的最大值翻轉至數組末位。至此完成了把最大值放到數組末位的操作;接下來只需要找到最小值位置,進行翻轉,將最小值放置數組首位即可。

package Week;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class W_5 {
	private static final int COLUMN_COUNT = 5;
	public static void main(String[] args){
        //讀取file中數據存到數組中
        System.out.println("獲取數據:");
        String pathname1 = "D:\\Java\\WorkSpaces\\LQB\\src\\Week\\data.txt"; // 絕對路徑或相對路徑都可以,這裏是絕對路徑,寫入文件時演示相對路徑
        File file = new File(pathname1); // 要讀取以上路徑的input。txt文件
        int[][] datas=null;
        int max,index,min;
        String res="";
        try {
			datas=intFileTOData(file);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        for(int i=0;i<datas.length;i++){
        	int[] test=new int[COLUMN_COUNT];
        	test=datas[i];
        	max=min=test[0];
        	index=0;
        	res="";//存儲結果
        	for(int j=0;j<test.length;j++){	//打印,找最大,最大值位置和最小值
        		System.out.print(test[j]+" ");
        		if(max<test[j]){
        			max=test[j];
        			index=j;
        		}
        		if(min>test[j]) min=test[j];
        	}
        	System.out.println();
        	
        	if(index!=(test.length-1)&&index!=0){
        		res=res+(index+1)+" ";
        		//翻轉數組
        		test=transtrate(test,index);
        	}else if(index==0){
        		res+="1 ";
        		test=transtrate(test,COLUMN_COUNT-1);
        	}
        		
        	for(int j=0;j<test.length;j++){
        		if(test[j]==min&&j!=0){
        			res+=(COLUMN_COUNT-j+" ");
        			break;
        		}
        	}
        	res=res+"0";
        	System.out.println(res);
        }
        
	}
	private static int[] transtrate(int[] test, int index) {
		// TODO Auto-generated method stub
		int[] temp=new int[test.length];
		for(int i=0;i<=index;i++){
			temp[i]=test[index-i];
		}
		for(int i=index+1;i<test.length;i++){
			temp[i]=test[i];
		}
		return temp;
	}
	public static int[][] intFileTOData(File file) throws Exception {
        /* 讀入TXT文件 */
        // String pathname = "trainData.txt"; //
        // 絕對路徑或相對路徑都可以,這裏是絕對路徑,寫入文件時演示相對路徑
        // File filename = new File(pathname); // 要讀取以上路徑的input。txt文件
        InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); // 建立一個輸入流對象reader
	    BufferedReader br = new BufferedReader(reader); // 建立一個對象,它把文件內容轉成計算機能讀懂的語言
	    int[][] doubleArray = null;
	    try{
			String line = null;
	        StringBuffer sb = new StringBuffer();
	        while ((line = br.readLine()) != null) {
	            sb.append(line).append("\n");
	        }
	        System.out.println("=============轉一維數組================");
	        String[] singleArray = sb.toString().split("\\s+");
	        // 遍歷一維數組
	        for (String str1 : singleArray) {
	            System.out.println(str1);
	        }
	
	        System.out.println("\n=============轉二維數組================");
	        int rows = singleArray.length / COLUMN_COUNT;// 數組行數
	        int num = -1;
	        doubleArray = new int[rows][COLUMN_COUNT];
	        for (int i = 0; i < rows; i++) {
	            for (int j = 0; j < COLUMN_COUNT; j++) {
	                doubleArray[i][j] =Integer.parseInt(singleArray[++num]);
	            }
	        }
	        // 遍歷二維數組
	        for (int i = 0; i < rows; i++) {
	            for (int j = 0; j < COLUMN_COUNT; j++) {
	                System.out.print(doubleArray[i][j] + "\t");
	            }
	            System.out.println();
	        }
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (br != null) {
	            try {
	                br.close();
	                br = null;
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
        return doubleArray;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章