2014年4月19日 星期六

Sudoku Solver



What is this?

This is a program which can solve sudoku for those people who are tired of solving difficult sudoku problem.

How to use?

1. Input the sudoku problem into the board.
2. Click "Solve It!" to solve sudoku, and you will see the answer on the board.
3. If you want to input another sudoku problem, just click "Clear" to clean the board and input again.

118 - Mutant Flatworld Explorers

Background

Robotics, robot motion planning, and machine learning are areas that cross the boundaries of many of the subdisciplines that comprise Computer Science: artificial intelligence, algorithms and complexity, electrical and mechanical engineering to name a few. In addition, robots as ``turtles'' (inspired by work by Papert, Abelson, and diSessa) and as ``beeper-pickers'' (inspired by work by Pattis) have been studied and used by students as an introduction to programming for many years.
This problem involves determining the position of a robot exploring a pre-Columbian flat world.

The Problem

Given the dimensions of a rectangular grid and a sequence of robot positions and instructions, you are to write a program that determines for each sequence of robot positions and instructions the final position of the robot.
A robot position consists of a grid coordinate (a pair of integers: x-coordinate followed by y-coordinate) and an orientation (N,S,E,W for north, south, east, and west). A robot instruction is a string of the letters 'L', 'R', and 'F' which represent, respectively, the instructions:
  • Left: the robot turns left 90 degrees and remains on the current grid point.
  • Right: the robot turns right 90 degrees and remains on the current grid point.
  • Forward: the robot moves forward one grid point in the direction of the current orientation and mantains the same orientation.
The direction North corresponds to the direction from grid point (x,y) to grid point (x,y+1).
Since the grid is rectangular and bounded, a robot that moves ``off'' an edge of the grid is lost forever. However, lost robots leave a robot ``scent'' that prohibits future robots from dropping off the world at the same grid point. The scent is left at the last grid position the robot occupied before disappearing over the edge. An instruction to move ``off'' the world from a grid point from which a robot has been previously lost is simply ignored by the current robot.

The Input

The first line of input is the upper-right coordinates of the rectangular world, the lower-left coordinates are assumed to be 0,0.
The remaining input consists of a sequence of robot positions and instructions (two lines per robot). A position consists of two integers specifying the initial coordinates of the robot and an orientation (N,S,E,W), all separated by white space on one line. A robot instruction is a string of the letters 'L', 'R', and 'F' on one line.
Each robot is processed sequentially, i.e., finishes executing the robot instructions before the next robot begins execution.
Input is terminated by end-of-file.
You may assume that all initial robot positions are within the bounds of the specified grid. The maximum value for any coordinate is 50. All instruction strings will be less than 100 characters in length.

The Output

For each robot position/instruction in the input, the output should indicate the final grid position and orientation of the robot. If a robot falls off the edge of the grid the word ``LOST'' should be printed after the position and orientation.

Sample Input

5 3
1 1 E
RFRFRFRF
3 2 N
FRRFLLFFRRFLL
0 3 W
LLFFFLFLFL

Sample Output

1 1 E
3 3 N LOST
2 3 S
 
出處: UVa Online Judge - Mutant Flatworld Explorers


問題敘述

此問題會先輸入兩個整數,表示這個矩形右上角的座標,接著會輸入多組測試資料,每組測試資料兩行,一直到輸入結束為止。每組測試資料第一行輸入的是兩個整數及一個字元,兩個整數代表機器人所在的初始的座標,字元表示面對的方位(E=東, W=西, S=南, N=北),第二行輸入的則是一行字串代表著一連串的指令(L=左轉, R=右轉, F=往現在面對的方位走一格)。每組輸入會對應一組輸出,此問題要求您輸出經過一連串的指令後,機器人最後所在的座標以及面對的方位為何。若機器人在執行指令的過程中跑出了此矩形的範圍,就輸出它在跑出去前的座標和方位並且印出 LOST,若機器人下次執行指令時,再次在之前跑出去過的座標往矩形外面跑,則此指令視為無效,將會被忽略。

解題思路

這是一個模擬類型的題目,沒有什麼特別的思路,但是要善用資料結構。比如說要如何知道左轉或右轉會轉到哪個方位呢? 我的作法是用一個陣列存{'E', 'N', 'W', 'S'},然後用一個 index 表示現在所在的位置,index + 1 就是左轉,index - 1 就是右轉,但是注意 index 做加減的時候可能會超出陣列範圍,所以要做環狀處理(意即 index 等於陣列的長度的時候要讓 index = 0,index 小於 0 的時候要讓 index = 陣列的長度 - 1)。其他的就把程式碼交給讀者們參考了。

c++ 程式碼

#include <iostream>
#include <map>
#include <vector>
using namespace std;

bool checkIsLost(int x, int y, int maxX, int maxY) {
    return x < 0 || x > maxX || y < 0 || y > maxY;
}

int main() {
    int maxX, maxY, x, y;
    char ori;
    string ins;
    char oriArr[4] = {'E', 'N', 'W', 'S'};
    int oriArrLen = 4;
    map<char, int> oriIndexMap;

    oriIndexMap['E'] = 0;
    oriIndexMap['N'] = 1;
    oriIndexMap['W'] = 2;
    oriIndexMap['S'] = 3;
    cin >> maxX >> maxY;
    vector< vector<bool> > lostTable(maxX + 1, vector<bool>(maxY + 1, false));
    while (cin >> x >> y >> ori >> ins) {
        int oriIndex;
        bool lost = false;

        oriIndex = oriIndexMap[ori];
        for (int i=0; i<ins.length(); i++) {
            switch (ins[i]) {
                case 'L':
                    oriIndex = (oriIndex + 1) % oriArrLen;
                    break;
                case 'R':
                    if (oriIndex)
                        oriIndex--;
                    else
                        oriIndex = oriArrLen - 1;
                    break;
                case 'F':
                    switch (oriIndex) {
                        case 0:
                            lost = checkIsLost(x + 1, y, maxX, maxY);
                            if (!lost)
                                x++;
                            break;
                        case 1:
                            lost = checkIsLost(x, y + 1, maxX, maxY);
                            if (!lost)
                                y++;
                            break;
                        case 2:
                            lost = checkIsLost(x - 1, y, maxX, maxY);
                            if (!lost)
                                x--;
                            break;
                        case 3:
                            lost = checkIsLost(x, y - 1, maxX, maxY);
                            if (!lost)
                                y--;
                    }
            }
            if (lost && !lostTable[x][y]) {
                lostTable[x][y] = true;
                break;
            }
        }
        cout << x << " " << y << " " << oriArr[oriIndex];
        if (lost)
            cout << " " << "LOST\n";
        else
            cout << endl;
    }

    return 0;
}

2014年4月7日 星期一

102 - Ecological Bin Packing

Background

Bin packing, or the placement of objects of certain weights into different bins subject to certain constraints, is an historically interesting problem. Some bin packing problems are NP-complete but are amenable to dynamic programming solutions or to approximately optimal heuristic solutions.
In this problem you will be solving a bin packing problem that deals with recycling glass.

The Problem

Recycling glass requires that the glass be separated by color into one of three categories: brown glass, green glass, and clear glass. In this problem you will be given three recycling bins, each containing a specified number of brown, green and clear bottles. In order to be recycled, the bottles will need to be moved so that each bin contains bottles of only one color.
The problem is to minimize the number of bottles that are moved. You may assume that the only problem is to minimize the number of movements between boxes.
For the purposes of this problem, each bin has infinite capacity and the only constraint is moving the bottles so that each bin contains bottles of a single color. The total number of bottles will never exceed 2^31.

The Input

The input consists of a series of lines with each line containing 9 integers. The first three integers on a line represent the number of brown, green, and clear bottles (respectively) in bin number 1, the second three represent the number of brown, green and clear bottles (respectively) in bin number 2, and the last three integers represent the number of brown, green, and clear bottles (respectively) in bin number 3. For example, the line 10 15 20 30 12 8 15 8 31
indicates that there are 20 clear bottles in bin 1, 12 green bottles in bin 2, and 15 brown bottles in bin 3.
Integers on a line will be separated by one or more spaces. Your program should process all lines in the input file.

The Output

For each line of input there will be one line of output indicating what color bottles go in what bin to minimize the number of bottle movements. You should also print the minimum number of bottle movements.
The output should consist of a string of the three upper case characters 'G', 'B', 'C' (representing the colors green, brown, and clear) representing the color associated with each bin.
The first character of the string represents the color associated with the first bin, the second character of the string represents the color associated with the second bin, and the third character represents the color associated with the third bin.
The integer indicating the minimum number of bottle movements should follow the string.
If more than one order of brown, green, and clear bins yields the minimum number of movements then the alphabetically first string representing a minimal configuration should be printed.

Sample Input

1 2 3 4 5 6 7 8 9
5 10 5 20 10 5 10 20 10

Sample Output

BCG 30
CBG 50

出處: UVa Online Judge - Ecological Bin Packing


問題敘述

此問題會有很多行輸入,每一行都會有九個整數,前三個整數分別代表在第一個回收桶裡棕色瓶子, 綠色瓶子和透明瓶子的數量,中間三個整數分別代表在第二個回收桶裡棕色瓶子, 綠色瓶子和透明瓶子的數量,最後三個整數分別代表在第三個回收桶裡棕色瓶子, 綠色瓶子和透明瓶子的數量。此問題要求您用最少的次數移動瓶子,來讓每個桶子都只裝一種顏色,並且輸出每個桶子各擺哪些顏色以及最少移動的次數。若不只一種移動方法可以讓每個桶子都只裝一種顏色且移動次數最少,則字母排列順序比較優先的要被輸出。

解題思路

因為瓶子的顏色只有三種,總共也只有六種排列方式,故暴力法是最簡單直接的解法。照字母順序把六種擺放瓶子顏色的方式都算出移動次數,並照順序找出移動次數最小的排列方式就是解答。

c++ 程式碼

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
    int start;

    while (cin >> start) {
        vector< vector<int> > binBottle(3, vector<int>(3, -1));
        vector<string> comb(6, "");
        map<string, int> getCount;
        string minComb;

        comb[0] = "BCG";
        comb[1] = "BGC";
        comb[2] = "CBG";
        comb[3] = "CGB";
        comb[4] = "GBC";
        comb[5] = "GCB";
        for (int i=0; i<binBottle.size(); i++) {
            for (int j=0; j<binBottle[i].size(); j++) {
                if (!i && !j)
                    binBottle[i][j] = start;
                else
                    cin >> binBottle[i][j];
            }
        }
        getCount[comb[0]] = binBottle[1][0] + binBottle[2][0] + binBottle[0][2] + binBottle[2][2] +
                            binBottle[0][1] + binBottle[1][1];
        getCount[comb[1]] = binBottle[1][0] + binBottle[2][0] + binBottle[0][1] + binBottle[2][1] +
                            binBottle[0][2] + binBottle[1][2];
        getCount[comb[2]] = binBottle[1][2] + binBottle[2][2] + binBottle[0][0] + binBottle[2][0] +
                            binBottle[0][1] + binBottle[1][1];
        getCount[comb[3]] = binBottle[1][2] + binBottle[2][2] + binBottle[0][1] + binBottle[2][1] +
                            binBottle[0][0] + binBottle[1][0];
        getCount[comb[4]] = binBottle[1][1] + binBottle[2][1] + binBottle[0][0] + binBottle[2][0] +
                            binBottle[0][2] + binBottle[1][2];
        getCount[comb[5]] = binBottle[1][1] + binBottle[2][1] + binBottle[0][2] + binBottle[2][2] +
                            binBottle[0][0] + binBottle[1][0];
        minComb = comb[0];
        for (int i=1; i<comb.size(); i++) {
            if (getCount[minComb] > getCount[comb[i]])
                minComb = comb[i];
        }
        cout << minComb << " " << getCount[minComb] << endl;
    }

    return 0;
}

2014年3月5日 星期三

Binary search

演算法類型

divide and conquer, 搜尋演算法

演算法目的

利用比對 key value 來對資料進行搜尋

演算法描述

使用 binary search 的前提是資料必須是已經排序好的,接著再藉由比對資料堆中間位置的 key value 來將資料堆做二分法搜尋。舉例說明,假設有一排序好的數列如下圖:



現在假設我們要搜尋的數字是 3,就我們目前所得知的資訊,3 有可能出現在此數列的任何位置,所以目前的搜尋範圍是整個數列,我們先找出在搜尋範圍內中間位置的數字,如下圖:


我們在中間位置找到 4,很明顯的 4 不是我們要的 3,不過因為數列是已經排序好的而且 3 < 4,故我們可以確定 3 只有可能落在 4 的左邊而不可能會落在 4 的右邊,如下圖:


如此我們就可以拋棄右邊,接著繼續向左邊搜尋,所以現在的搜尋範圍變成只剩 4 的左邊,同之前的方法,直接去比對搜尋範圍中間位置的數字,如下圖:


我們在搜尋範圍中間找到 2,很明顯 2 不是我們要的 3,不過因為數列是已經排序好的而且 3 > 2,故我們可以確定 3 只有可能落在 2 的右邊而不可能會落在 2 的左邊,如下圖:


同之前的方法,我們繼續在搜尋範圍內找中間的數字做比對,以目前的情況來看,我們只剩下一個數字,如下圖:


恭喜,我們很幸運的找到 3 了,binary search 圓滿結束。如果一直二分到沒有範圍可以搜尋,則代表此數字不在數列裡。

最壞情況效率分析

設總資料量為 n, 分析單位為比較次數
binary search 的最壞情況就是要搜尋的資料不在資料堆裡,依據最壞情況可以列出以下遞迴式:

T(n) = T(n / 2) + 1
T(1) = 1

根據 master theorem,可推出此演算法效率的最壞情況為 O(lgn)

程式實作


C
#include <stdio.h>

int binarySearch(int *, int, int);

int main() {
    int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    int arrLength = 8;
    int findNum = 3;
    int findIndex = binarySearch(arr, arrLength, findNum);

    if (findIndex == -1)
        printf("The number %d is not in the sequence\n", findNum);
    else
        printf("The number %d is at index %d\n", findNum, findIndex);

    return 0;
}

int binarySearch(int *arr, int arrLength, int findNum) {
    int low = 0;
    int high = arrLength - 1;

    while (low <= high) {
        int mid = (low + high) / 2;

        if (findNum > arr[mid])
            low = mid + 1;
        else if (findNum == arr[mid])
            return mid;
        else
            high = mid - 1;
    }
    return -1;
}

Java
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
        int findNum = 3;
        int findIndex = binarySearch(arr, findNum);

        if (findIndex == -1)
            System.out.printf("The number %d is not in the sequence\n", findNum);
        else
            System.out.printf("The number %d is at index %d\n", findNum, findIndex);
    }

    private static int binarySearch(int[] arr, int findNum) {
        int low = 0;
        int high = arr.length - 1;

        while (low <= high) {
            int mid = (low + high) / 2;

            if (findNum > arr[mid])
                low = mid + 1;
            else if (findNum == arr[mid])
                return mid;
            else
                high = mid - 1;
        }
        return -1;
    }
}

Python
def binarySearch(arr, findNum):
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) / 2
        if findNum > arr[mid]:
            low = mid + 1
        elif findNum == arr[mid]:
            return mid
        else:
            high = mid - 1
    return -1

arr = [1, 2, 3, 4, 5, 6, 7, 8]
findNum = 3
findIndex = binarySearch(arr, findNum)
if findIndex == -1:
    print "The number %d is not in the sequence" % (findNum)
else:
    print "The number %d is at index %d" % (findNum, findIndex)

2014年3月1日 星期六

Merge sort

演算法類型

divide and conquer, 排序演算法

演算法目的

利用比較 key value 來將資料做排序

演算法描述

merge sort 的核心觀念是將大筆資料切割成很多小筆資料做排序,接著利用已經排序好的小筆資料合併成排序好的大筆資料。merge sort 的概觀流程圖如下:


分割步驟相信大家應該沒有什麼問題,就是一次將資料切一半。比較需要解釋的應該是合併步驟,以下舉例說明合併步驟如何進行,假設要合併 A 和 B 兩個已排序好的數列,如下圖:


現在我們將兩個箭頭各指著 A 數列和 B 數列的第一個元素,如下圖:


將箭頭指到的數字做比較,把比較小的數字複製到另外一個 C 數列,並且將指向比較小的數字的箭頭往前移一格,如下圖:


繼續重複剛剛的動作,如下圖:


繼續重複這個動作直到有其中一個箭頭超出數列的範圍為止,如下圖:





現在 B 數列的箭頭已經超出範圍了,所以我們剩下要做的事情就只是把 A 數列箭頭開始以後的數字全部複製到 C 數列就可以了,如下圖:



這樣 C 數列就是一個合併完成的數列了。

最壞情況時間複雜度分析

設總資料量為 n, 分析單位為比較次數
依據此演算法的最壞情況,我們可以列出以下遞迴式:

T(n) = 2T(n / 2) + n - 1
T(1) = 0

根據 master theorem,可以求出此演算法為 O(nlgn) 的演算法

程式實作


C
#include <stdio.h>

void mergeSort(int *, int, int);
void merge(int *, int, int, int);

int main() {
    int arr[8] = {4, 6, 1, 9, 5, 3, 0, 2};
    int dataNum = 8;
    int i;

    printf("before sorting: ");
    for (i=0; i<dataNum; i++)
        printf("%d " , arr[i]);
    printf("\n");
    mergeSort(arr, 0, dataNum - 1);
    printf("after sorting: ");
    for (i=0; i<dataNum; i++)
        printf("%d " , arr[i]);
    printf("\n");

    return 0;
}

void mergeSort(int *arr, int low, int high) {
    if (low < high) {
        int mid = (low + high) / 2;

        mergeSort(arr, low, mid);
        mergeSort(arr, mid + 1, high);
        merge(arr, low, mid, high);
    }
}

void merge(int *arr, int low, int mid, int high) {
    int leftIndex = low;
    int rightIndex = mid + 1;
    int tempArrLength = high - low + 1;
    int tempArr[tempArrLength];
    int tempIndex = 0;

    while (leftIndex <= mid && rightIndex <= high) {
        if (arr[leftIndex] <= arr[rightIndex]) {
            tempArr[tempIndex] = arr[leftIndex];
            leftIndex++;
        }
        else {
            tempArr[tempIndex] = arr[rightIndex];
            rightIndex++;
        }
        tempIndex++;
    }
    if (leftIndex > mid) {
        while (rightIndex <= high) {
            tempArr[tempIndex] = arr[rightIndex];
            rightIndex++;
            tempIndex++;
        }
    }
    else {
        while (leftIndex <= mid) {
            tempArr[tempIndex] = arr[leftIndex];
            leftIndex++;
            tempIndex++;
        }
    }
    leftIndex = low;
    for (tempIndex=0; tempIndex<tempArrLength; tempIndex++) {
        arr[leftIndex] = tempArr[tempIndex];
        leftIndex++;
    }
}

Java
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {4, 6, 1, 9, 5, 3, 0, 2};

        System.out.print("before sorting: ");
        for (int num: arr)
            System.out.printf("%d " , num);
        System.out.println();
        mergeSort(arr, 0, arr.length - 1);
        System.out.print("after sorting: ");
        for (int num: arr)
            System.out.printf("%d " , num);
        System.out.println();
    }

    private static void mergeSort(int[] arr, int low, int high) {
        if (low < high) {
            int mid = (low + high) / 2;

            mergeSort(arr, low, mid);
            mergeSort(arr, mid + 1, high);
            merge(arr, low, mid, high);
        }
    }

    private static void merge(int[] arr, int low, int mid, int high) {
        int leftIndex = low;
        int rightIndex = mid + 1;
        int[] tempArr = new int[high - low + 1];
        int tempIndex = 0;

        while (leftIndex <= mid && rightIndex <= high) {
            if (arr[leftIndex] <= arr[rightIndex]) {
                tempArr[tempIndex] = arr[leftIndex];
                leftIndex++;
            }
            else {
                tempArr[tempIndex] = arr[rightIndex];
                rightIndex++;
            }
            tempIndex++;
        }
        if (leftIndex > mid) {
            while (rightIndex <= high) {
                tempArr[tempIndex] = arr[rightIndex];
                rightIndex++;
                tempIndex++;
            }
        }
        else {
            while (leftIndex <= mid) {
                tempArr[tempIndex] = arr[leftIndex];
                leftIndex++;
                tempIndex++;
            }
        }
        leftIndex = low;
        for (int temp: tempArr) {
            arr[leftIndex] = temp;
            leftIndex++;
        }
    }
}

Python
def merge(arr, low, mid, high):
    leftIndex = low
    rightIndex = mid + 1
    tempArr = []
    while leftIndex <= mid and rightIndex <= high:
        if arr[leftIndex] <= arr[rightIndex]:
            tempArr.append(arr[leftIndex])
            leftIndex += 1
        else:
            tempArr.append(arr[rightIndex])
            rightIndex += 1
    if leftIndex > mid:
        while rightIndex <= high:
            tempArr.append(arr[rightIndex])
            rightIndex += 1
    else:
        while leftIndex <= mid:
            tempArr.append(arr[leftIndex])
            leftIndex += 1
    leftIndex = low
    for temp in tempArr:
        arr[leftIndex] = temp
        leftIndex += 1

def mergeSort(arr, low, high):
    if low < high:
        mid = (low + high) / 2
        mergeSort(arr, low, mid)
        mergeSort(arr, mid + 1, high)
        merge(arr, low, mid, high)

arr = [4, 6, 1, 9, 5, 3, 0, 2]
print "before sorting:",
for num in arr:
    print "%d" % (num),
print ""
mergeSort(arr, 0, len(arr) - 1)
print "after sorting:",
for num in arr:
    print "%d" % (num),
print ""

2014年2月27日 星期四

Selection sort

演算法類型

貪婪演算法, 排序演算法

演算法目的

藉由比較key value來將資料做排序

演算法描述

selection sort的精神是將資料切成兩部份,一部份爲已排序另一部份則是尚未排序,並且每次於尚未排序的資料堆中找出key value最小的資料放入已排序資料堆中的最後一個位置。舉例來說,有個數列如下:


現在此數列所有的數字都在未排序的資料堆裡,我們可以由左至右對數列做一次掃描,找出最小的數字1,並且將它與數列的第一個數字3做交換,這樣我們就可以把1歸納在已排序的資料堆裡,如下圖:



接著繼續從剩下未排序的資料堆裡,找出最小的數字3,並且將它與未排序資料堆的第一個數字5做交換,這樣就可以讓3被歸納在已排序的資料堆裡,如下圖:





再繼續從剩下未排序的資料堆裡,找出最小的數字4,並且將它與未排序資料堆的第一個數字9做交換,這樣就可以讓4被歸納在已排序的資料堆裡,如下圖:




依此類推,不斷地重複這些步驟就可以把全部的資料都排序好了。

效率分析

設總資料量爲n, 分析單位爲比較次數

第一次掃描找到最小值的比較次數: n - 1次
第二次掃描找到最小值的比較次數: n - 2次
第三次掃描找到最小值的比較次數: n - 3次

 ...

第n次掃描找到最小值的比較次數: 0次

總共比較次數: (0 + n - 1) * n / 2 = (n ^ 2 - n) / 2
故此演算法屬於O(n ^ 2)

程式實作


C
#include <stdio.h>

void selSort(int *, int);

int main() {
    int arr[8] = {3, 5, 9, 10, 8, 1, 12, 4};
    int dataNum = 8;
    int i;

    printf("before sorting: ");
    for (i=0; i<dataNum; i++)
        printf("%d ", arr[i]);
    printf("\n");
    selSort(arr, dataNum);
    printf("after sorting: ");
    for (i=0; i<dataNum; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}

void selSort(int *arr, int dataNum) {
    int i, j;

    for (i=0; i<dataNum; i++) {
        int smallestIndex = i;

        for (j=i+1; j<dataNum; j++) {
            if (arr[smallestIndex] > arr[j])
                smallestIndex = j;
        }
        if (smallestIndex != i) {
            int temp = arr[smallestIndex];

            arr[smallestIndex] = arr[i];
            arr[i] = temp;
        }
    }
}

Java
public class SelSort {
    public static void main(String[] args) {
        int[] arr = {3, 5, 9, 10, 8, 1, 12, 4};

        System.out.print("before sorting: ");
        for (int num: arr)
            System.out.printf("%d ", num);
        System.out.println();
        selSort(arr);
        System.out.print("after sorting: ");
        for (int num: arr)
            System.out.printf("%d ", num);
        System.out.println();
    }

    private static void selSort(int[] arr) {
        for (int i=0; i<arr.length; i++) {
            int smallestIndex = i;

            for (int j=i+1; j<arr.length; j++) {
                if (arr[smallestIndex] > arr[j])
                    smallestIndex = j;
            }
            if (smallestIndex != i) {
                int temp = arr[smallestIndex];

                arr[smallestIndex] = arr[i];
                arr[i] = temp;
            }
        }
    }
}

Python
def selSort(arr):
    for i in range(len(arr)):
        smallestIndex = i

        for j in range(i + 1, len(arr)):
            if arr[smallestIndex] > arr[j]:
                smallestIndex = j
        if smallestIndex != i:
            temp = arr[smallestIndex]
            arr[smallestIndex] = arr[i]
            arr[i] = temp

arr = [3, 5, 9, 10, 8, 1, 12, 4]
print "before sorting:",
for num in arr:
    print num,
print ""
selSort(arr)
print "after sorting:",
for num in arr:
    print num,
print ""

2014年2月8日 星期六

101 - The Blocks Problem


Background 

Many areas of Computer Science use simple, abstract domains for both analytical and empirical studies. For example, an early AI study of planning and robotics (STRIPS) used a block world in which a robot arm performed tasks involving the manipulation of blocks.
In this problem you will model a simple block world under certain rules and constraints. Rather than determine how to achieve a specified state, you will ``program'' a robotic arm to respond to a limited set of commands.

The Problem 

The problem is to parse a series of commands that instruct a robot arm in how to manipulate blocks that lie on a flat table. Initially there are nblocks on the table (numbered from 0 to n-1) with block bi adjacent to block bi+1 for all $0 \leq i < n-1$ as shown in the diagram below:

\begin{figure}
\centering
\setlength{\unitlength}{0.0125in} %
\begin{picture}
(2...
...raisebox{0pt}[0pt][0pt]{$\bullet
\bullet \bullet$ }}}
\end{picture}
\end{figure}
Figure: Initial Blocks World

The valid commands for the robot arm that manipulates blocks are:
  • move a onto bwhere a and b are block numbers, puts block a onto block b after returning any blocks that are stacked on top of blocks a and b to their initial positions.
  • move a over bwhere a and b are block numbers, puts block a onto the top of the stack containing block b, after returning any blocks that are stacked on top of block a to their initial positions.
  • pile a onto bwhere a and b are block numbers, moves the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto block b. All blocks on top of block b are moved to their initial positions prior to the pile taking place. The blocks stacked above block aretain their order when moved.
  • pile a over bwhere a and b are block numbers, puts the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto the top of the stack containing block b. The blocks stacked above block a retain their original order when moved.
  • quitterminates manipulations in the block world.
Any command in which a = b or in which a and b are in the same stack of blocks is an illegal command. All illegal commands should be ignored and should have no affect on the configuration of blocks.

The Input 

The input begins with an integer n on a line by itself representing the number of blocks in the block world. You may assume that 0 < n < 25.
The number of blocks is followed by a sequence of block commands, one command per line. Your program should process all commands until the quit command is encountered.
You may assume that all commands will be of the form specified above. There will be no syntactically incorrect commands.

The Output 

The output should consist of the final state of the blocks world. Each original block position numbered i ( $0 \leq i < n$ where n is the number of blocks) should appear followed immediately by a colon. If there is at least a block on it, the colon must be followed by one space, followed by a list of blocks that appear stacked in that position with each block number separated from other block numbers by a space. Don't put any trailing spaces on a line.
There should be one line of output for each block position (i.e., n lines of output where n is the integer on the first line of input).

Sample Input 

10
move 9 onto 1
move 8 over 1
move 7 over 1
move 6 over 1
pile 8 over 6
pile 8 over 5
move 2 over 1
move 4 over 9
quit

Sample Output 

 0: 0
 1: 1 9 2 4
 2:
 3: 3
 4:
 5: 5 8 7 6
 6:
 7:
 8:
 9:

出處: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=37



問題敘述

此問題首先會輸入積木的個數,接著會輸入一連串的指令來告訴機器手臂該如何搬動積木,一直到輸入quit才結束。假設積木的總數量為n,積木會從0開始編號到n-1,指令的形式為: move/pile 積木編號 onto/over 積木編號,舉例: move 9 onto 1 意思就是把9號積木移動到1號積木的上面,若9號積木或1號積木上面有其他積木,就把上面的積木都移回原位。move 8 over 1 意思就是把8號積木移動到有1號積木的積木堆上面,若8號積木上面有其他積木,就把上面的積木都移回原位。pile 8 onto 6 意思就是把8號以上的積木全部移動到6號積木的上面,若6號積木上面有其他積木,就把上面的積木都移回原位。pile 8 over 6 意思就是把8號以上積木全部移動到有6號積木的積木堆上面。

解題思路

沒有什麼特別的思路,照著做就可以求解。不過在寫程式上卻有一些技巧,因為很多指令的動作是有重複的,所以可以把它寫成function呼叫。比如說"將某個積木上面的所有積木搬回原位"這個動作是很常用到的,所以可以寫成function比較方便。還有要注意的一點是如果指令裡的2個積木編號是在同一個積木堆上,則此指令無效,必須忽略此指令否則會wrong answer。

c++ 程式碼

#include <iostream>
#include <vector>
using namespace std;

void moveBackToOri(vector< vector<int> >& blocks, vector<int>& blockPos, int pos, int theBlock) {
    while (blocks[pos].back() != theBlock) {
        int last = blocks[pos].back();

        blocks[pos].pop_back();
        blocks[last].push_back(last);
        blockPos[last] = last;
    }
}

void pileBlocks(vector< vector<int> >& blocks, vector<int>& blockPos, int pos, int theBlock, vector<int>& temp) {
    while (true) {
        int last = blocks[pos].back();

        blocks[pos].pop_back();
        temp.push_back(last);
        if (last == theBlock)
            break;
    }
}

int main() {
    int blockNum;

    cin >> blockNum;
    vector< vector<int> > blocks(blockNum, vector<int>());
    vector<int> blockPos(blockNum, -1);
    for (int i=0; i<blocks.size(); i++) {
        blocks[i].push_back(i);
        blockPos[i] = i;
    }
    while (true) {
        string action, where;
        int fromBlock, toBlock;
        int fromPos;
        int toPos;

        cin >> action;
        if (action == "quit")
            break;
        cin >> fromBlock >> where >> toBlock;
        fromPos = blockPos[fromBlock];
        toPos = blockPos[toBlock];
        if (fromPos != toPos) {
            if (action == "move") {
                if (where == "onto") {
                    moveBackToOri(blocks, blockPos, fromPos, fromBlock);
                    moveBackToOri(blocks, blockPos, toPos, toBlock);
                    blocks[fromPos].pop_back();
                    blocks[toPos].push_back(fromBlock);
                    blockPos[fromBlock] = toPos;
                }
                else {
                    moveBackToOri(blocks, blockPos, fromPos, fromBlock);
                    blocks[fromPos].pop_back();
                    blocks[toPos].push_back(fromBlock);
                    blockPos[fromBlock] = toPos;
                }
            }
            else {
                vector<int> temp;

                if (where == "onto") {
                    pileBlocks(blocks, blockPos, fromPos, fromBlock, temp);
                    moveBackToOri(blocks, blockPos, toPos, toBlock);
                    while (!temp.empty()) {
                        int last = temp.back();

                        temp.pop_back();
                        blocks[toPos].push_back(last);
                        blockPos[last] = toPos;
                    }
                }
                else {
                    pileBlocks(blocks, blockPos, fromPos, fromBlock, temp);
                    while (!temp.empty()) {
                        int last = temp.back();

                        temp.pop_back();
                        blocks[toPos].push_back(last);
                        blockPos[last] = toPos;
                    }
                }
            }
        }
    }
    for (int i=0; i<blocks.size(); i++) {
        cout << i << ":";
        for (int j=0; j<blocks[i].size(); j++)
            cout << " " << blocks[i][j];
        cout << endl;
    }

    return 0;
}

2014年2月1日 星期六

105 - The Skyline Problem



出處: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=41


問題敘述

此問題會輸入很多組長方形建築物的資料,每組資料分別是: 左x座標, 高度, 右x座標,輸入資料會照著左x座標由小到大排序,得到所有建築物的資料之後,必須輸出"天際線向量"。所謂天際線向量,就是用一個長的像這樣子的向量: (v1, v2, v3, ... , vn) 來表示天際線,奇數位置填的是x座標,偶數位置填的是高度,必須從最小的x座標開始填起。

解題思路

這題有一個可以減少我們很多功夫的關鍵點,那就是所有座標都是小於10,000的整數,也就是說我們只要開一個10,000個元素的陣列,暴力記下每一個x座標的最高點,就可以完成天際線向量了。所以此題的演算法大致上是如此: 每讀入一組建築物資料,就更新那一區塊的所有x座標的最高點(注意不要更新到建築物最右邊座標的高度,因為這樣才能知道哪個x座標開始產生高度變化),最後只要從小到大把每個x座標的最高點掃描一遍,就可以印出天際線向量了。

c++ 程式碼

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int left, right, height, last;
    int first = -1;
    int nowHeight = 0;
    vector<int> heightVec(10000, 0);

    while (cin >> left >> height >> right) {
        if (first == -1) {
            first = left;
            last = right;
        }
        if (right > last)
            last = right;
        for (int i=left; i<right; i++) {
            if (height > heightVec[i])
                heightVec[i] = height;
        }
    }
    for (int i=first; i<=last; i++) {
        if (heightVec[i] != nowHeight) {
            cout << i << " " << heightVec[i];
            if (i == last)
                cout << endl;
            else {
                cout << " ";
                nowHeight = heightVec[i];
            }
        }
    }

    return 0;
}