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;
}