Showing posts with label 程式設計. Show all posts
Showing posts with label 程式設計. Show all posts

Tuesday, August 7, 2012

3 different way Tree Traversal

=========================================================================
Node class for tree
class Node{
    int data;
    Node left;
    Node right;
}
=========================================================================
Case 1: pre-order 

Recursive
public static void preOrderRecursive(Node root){
    if(root == null)
        return;
		
    System.out.print(root.data + " ");		
    preOrderRecursive(root.left);
    preOrderRecursive(root.right);
}
NON-Recursive
public static void preOrderIterative(Node root){
    if(root == null)
        return;
		
    Stack<Node> unvisited = new Stack<Node>();
    unvisited.push(root);
	
    while(!unvisited.isEmpty()){
        Node node = unvisited.pop();
			
        System.out.print(node.data + " ");
        if(node.right != null)
            unvisited.push(node.right);
        if(node.left != null)
            unvisited.push(node.left);
    }	
}
=========================================================================
Case 2: in-order 

Recursive
public static void inOrderRecursive(Node root){
    if(root == null)
        return;	
	
    inOrderRecursive(root.left);
    System.out.print(root.data + " ");
    inOrderRecursive(root.right);
}
NON-Recursive
public static void inOrderIterative(Node root){
    if(root == null)
        return;
		
    Stack<Node> unvisited = new Stack<Node>();
		
    while(!unvisited.isEmpty() || root != null){
        if(root != null){
            unvisited.push(root);
            root = root.left;
        }else{
            root = unvisited.pop();
            System.out.print(root.data + " ");
            root = root.right;
        }
    }
}
========================================================================= 
Case 3: post-order 

Recursive
public static void postOrderRecursive(Node root){
    if(root == null)
        return;
		
    postOrderRecursive(root.left);
    postOrderRecursive(root.right);
    System.out.print(root.data + " ");		
}
NON-Recursive
public static void postOrderIterative(Node root){
    if(root == null)
        return;
		
    Stack<Node> finalStack = new Stack<Node>();
    Stack<Node> tempStack = new Stack<Node>();
	
    tempStack.push(root);
    while(!tempStack.isEmpty()){
        Node node = tempStack.pop();
        finalStack.push(node);
        if(node.left != null)
            tempStack.push(node.left);
				
        if(node.right != null)
            tempStack.push(node.right);
    }
	
    while(!finalStack.isEmpty()){
        Node node = finalStack.pop();
        System.out.print(node.data + " ");	
    }
}

Find a missing integer in an array of number

Find a missing integer in an array of number

Case 1: Sorted
Use two pointers to store previous and current value, and difference between two number should equal to 1.
public static int findMissing_Sorted(int[] input){
    if(input.length == 0)
        return 0;

    int prev = input[0];
    for(int i = 1 ; i < input.length ; i++){
        int curr = input[i];
        if((curr - prev) != 1)
            return (prev + 1);
        else
            prev = curr;
    }
    return 0;
}



Case 2: Unsorted
Get the sum of 1 to N, use formula sum = (N+1)*(N)/2
Minus the element in the array, and the remaining value is the missing number.
public static int findMissing_Unsorted(int[] input){
    if(input.length == 0)
        return 0;
   
    int N = 10;
    int max = (N + 1) * N / 2;
  
    for(int i = 0 ; i < input.length ; i++)
        max -= input[i];
   
    return max;
}

Monday, August 6, 2012

How to use *args and **kwargs in Python

from
http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

http://docs.python.org/tutorial/controlflow.html#keyword-arguments


def test_var_args(farg, *args):
    print "formal arg:",farg
    for arg in args:
        print  "another arg:",arg
  


def test_var_kwargs(farg, **kwargs):
    print "formal arg:",farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

test_var_args(1, "two", 3, "four")
print '-'*40
test_var_kwargs(farg = 1, myarg2 = "two", myarg3 = 3, myarg4 = "four")


def test_var_args_call(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

args = ("two", 3)
test_var_args_call(1, *args)


def test_var_args_call(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

kwargs = {"arg3": 3, "arg2": "two"}
test_var_args_call(1, **kwargs)

Tuesday, July 31, 2012

Codeforce - 158A - Next Round

n, k = map(int, raw_input().strip().split() )
seq = map(int, raw_input().strip().split() )

score = seq[k - 1]

if score == 0:
    counter = 0
    for i in range(0, k):
        if seq[i] > score:
            counter += 1
    print counter
 
else:
    counter = k
    for i in range(k, n):
        if seq[i] >= score:
            counter += 1
        else:
            break
    print counter

ACM105 -- The Skyline Problem

#include <iostream>

using namespace std;

int main()
{
    int L,H,R;
    int counter = 0;
    int temp_pre,temp_curr;
    int min = 20000,max = 0;
    int building[10001] = {0};


    while(cin>>L>>H>>R)
    {
        if(min>L)
        min = L;

        if(max<R)
        max = R;

        for(int i = L ; i < R ; i++)
        {
            if(building[i] < H)
            building[i] = H;
        }
        counter++;
    }



    bool check = true;
    temp_pre = building[min];
    cout<<min<<" "<<temp_pre<<" ";

    for(int j = min+1 ; j <= max ; j++)
    {
        temp_curr = building[j];
        if(check) //check == true
        {
            if(temp_curr == 0)
            {
                check = false;
                cout<<j<<" "<<temp_curr;
            }else
            {
                if(temp_curr != temp_pre)
                {
                    cout<<j<<" "<<temp_curr<<" ";
                    temp_pre = temp_curr;
                }
            }
        }
        else
        {
            if(temp_curr == 0)
            {
                //do nothing
            }else
            {
                check = true;
                temp_pre = temp_curr;
                cout<<" "<<j<<" "<<temp_curr<<" ";
            }
        }
    }

    cout<<endl;
    return 0;
}

Codeforces -- 1A -- Theater Square

#include <iostream>
#include <math.h>

using namespace std;

int main(int argc, char* argv[]){
    long double n,m,a;

    cin>>n>>m>>a;

    long long res = (long long)(ceil(n/a) * ceil(m/a));

    cout<<res;
 return 0;
}

ACM 10035 -- Primary Arithmetic

#include <iostream>

using namespace std;


int main(int argc, char* argv[]){
    unsigned long long n1;
    unsigned long long n2;
    int carry = 0;
    int sum = 0;
    int count = 0;

    while(cin >> n1 >> n2) {
        if(n1 == 0 & n2 == 0)
            break;

        carry = 0;
        count = 0;
        sum = 0;

        while ((n1 > 0) || (n2 > 0)) {

            sum = carry + (n1 % 10) + (n2 % 10);

            if (sum >= 10) {
                count++;
            }

            carry = sum / 10;

            n1 /= 10;
            n2 /= 10;
        }

        if (count == 0) {
            cout << "No carry operation." << endl;
        } else if (count == 1) {
            cout << "1 carry operation." << endl;
        } else {
            cout << count << " carry operations." << endl;
        }
    }
 return 0;
}

ACM 494 -- Kindergarten Counting Game

#include <stdio.h>
#include <ctype.h>


int main()
{
    char temp;
    int counter = 0;
    int isWord = 0;
    while((temp = getchar()) != EOF){
        if(temp == '\n'){
            printf("%d\n", counter);
            counter = 0;
            isWord = 0;
        }else{
            if((temp >= 65 && temp <= 90)||(temp >= 97 && temp <= 122)){
                if(isWord == 0){
                    isWord = 1;
                    counter++;
                }
            }else{
                if(isWord == 1){
                    isWord = 0;
                }
            }
        }
    }
    return 0;
}

ACM 10038 -- Jolly Jumpers

#include <stdio.h>
#include <math.h>


int main(int argc, char* argv[])
{
    int counter;
    int num[3000];
    int flag[3000];

    while( scanf("%d", &counter) == 1 ){
        int i;
 for(i = 0 ; i < counter ; i++){
            scanf("%d", &num[i]);
            flag[i] = 0;
        }

        int res = 0;
        for(i = 1 ; i < counter ; i++){
            int diff;
            if(num[i] > num[i-1]){
                diff = num[i] - num[i-1];
            }else{
                diff = num[i-1] - num[i];
            }

            if(0 < diff && diff < counter){
                if(flag[diff] == 0){
                    flag[diff] = 1;
                }else{
                    res = 1;
                    break;
                }
            }else{
                res = 1;
                break;
            }

        }

        if( res == 1 ){
            printf("Not jolly\n");
        }
        else{
            printf("Jolly\n");
        }
    }
 return 0;
}

ACM 458 -- The Decoder

#include <stdio.h>
#include <ctype.h>


int main()
{
    char temp;
    while((temp=getchar())!=EOF)
    {
        (temp == '\n') ? putchar(temp) : putchar(temp-7);
    }
    return 0;
}

ACM 272 -- TEX Quotes

#include <stdio.h>
#include <ctype.h>


int main()
{
    char temp;
    int pair = 0;
    while((temp=getchar())!=EOF){
        if(temp == '"'){
            if(pair == 0){
                pair++;
                printf("``");
            }else{
                pair = 0;
                printf("''");
            }
        }else{
            putchar(temp);
        }
    }
    return 0;
}

ACM 10071 -- Back to High School Physics

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int v, t;
    while (scanf("%d %d",&v, &t)!= EOF){
        printf("%d\n", 2*v*t);
    }
    return 0;
}

ACM 10055 -- Hashmat the Brave Warrior

#include <stdio.h>


int main()
{
    long long int hash, oppen;
    while (scanf("%lld %lld",&hash, &oppen)!= EOF){
        if(hash > oppen)
            printf("%lld\n", (hash - oppen));
        else
            printf("%lld\n", (oppen - hash));
    }
    return 0;
}


ACM 10110 -- Light, more light

#include <iostream>
#include <math.h>
#include <sstream>
#include <stdio.h>
#include <cstdio>

using namespace std;

bool willLight(double num){
    long long int test = (int) sqrt(num) ;

    if(test*test == num)
        return true;


    return false;
}


int main()
{
    double input;

    while(scanf("%lf", &input)){
        if(input == 0.0)
            break;

        if( willLight(input) )
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }

    return 0;
}

ACM 492 -- Pig-Latin

#include <stdio.h>
#include <ctype.h>
int test(char ch);

int main()
{
    int i;
    char ch;
    char root;
    int s;

    while(1){
        i = 0;
        while(1){
            ch = getchar();
            if(ch == EOF)
                return 0;
            if(isalpha(ch)){
                if(!i){
                    s = test(ch);

                    if(s)
                        printf("%c", ch);
                    else
                        root = ch;
                    i++;
    }else{
                    printf("%c", ch);
                }
            }else{
                if(!i){
                    printf("%c", ch);
                    break;
                }
                if(s){
                    printf("ay%c", ch);
                }else{
                    printf("%cay%c", root, ch);
                }
                break;
            }
        }
    }
    return 0;
}

int test(char ch){
 if(ch == 'A' || ch == 'a')
  return 1;
 if(ch == 'E' || ch == 'e')
  return 1;
 if(ch == 'I' || ch == 'i')
  return 1;
 if(ch == 'O' || ch == 'o')
  return 1;
 if(ch == 'U' || ch == 'u')
  return 1;

 return 0;
}


Tuesday, March 20, 2012

Grid Walk

Challenge Description
There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself?

InputThere is no input for this program.

Output
Print out the how many points can the monkey access. (The number should be printed as an integer whole number eg.
if the answer is 10 (its not !!), print out 10, not 10.0 or 10.00 etc)

exist = []
point = {}

#make sure the sum of digit is less or equal than 19
def belowUpper(x, y):
    if x<0 or y<0:
        return False
    abs_x = str(abs(x))
    abs_y = str(abs(y))
    sum_x = 0
    sum_y = 0
    for c in abs_x:
        sum_x = sum_x + int(c)
    for c in abs_y:
        sum_y = sum_y + int(c)

    if sum_x + sum_y <= 19:
        return True



#check the point is valid or not
def addToList(x, y):
    if belowUpper(x+1, y):
        tmp = str(x+1) + " " + str(y)
        try:
            point[tmp]
        except:
            point[tmp] = 1
            exist.append([x+1, y])
        
        
    if belowUpper(x, y+1):
        tmp = str(x) + " " + str(y+1)
        try:
            point[tmp]
        except:
            point[tmp] = 1
            exist.append([x, y+1])




#remove overlap part when x = 0 or y = 0
def removeOverlap(x, y):
    total = 0
    xx = x
    yy = y
    while True:
        if belowUpper(xx, yy):
           total += 1
           xx += 1
        else:
            break

    return total
    

#main function
exist.append([0,0])

start = 0

while True:
    addToList(exist[start][0],exist[start][1])
    start+=1
    if start >= len(exist):
        break

over = removeOverlap(0, 0)

print (len(exist) - (over)) * 4 + 1

Tuesday, February 7, 2012

ACM 10062 -- Tell me the frequencies!


#include <iostream>

using namespace std;
void checkunique(string str);
bool first;

int main()
{
    string input;
    first = true;
    //while(cin>>input)
    while(getline(cin, input)){
        if(first == false)
            cout<<endl;
        checkunique(input);
        first = false;
    }
    return 0;
}


void checkunique(string str){
    int char_set[256] = {0};
    for(int i = 0 ; i < str.length() ; i ++){
        int val = str[i];
  char_set[val]++;

    }

    for(int i = 1 ; i <= str.length() ; i ++){
        for(int j = 256 ; j >= 0 ; j--){
            if(char_set[j] == i){
                cout<<j<<" "<<i<<endl;
            }
        }
    }
}

Friday, November 19, 2010

ACM-392 Polynomial Showdown with C++


#include <iostream>
#include <sstream>
#include <list>


using namespace std;
string showExponentSP(int temp, int item); //用來處理輸入裡面最先出現的項次
string showExponent(int temp, int item);   //用來處理剩下的項次
//item 表示"項次"
//temp 表示"輸入的值"


int main()
{
    string str = "";
    list<int> l;

    int input;
    int counter = 0;
    int level = 8;

    cin>>input;

    while( cin )
    {
        l.push_back(input);
        counter++;

        if(counter == 9)
        {
            list<int>::iterator iter = l.begin();
            while( iter != l.end() ) {
                if(str.empty())
                {
                    str.append(showExponentSP(*iter,level));
                }
                else
                {
                    str.append(showExponent(*iter,level));
                }
                ++iter;
                level--;
            }

            cout<<str<<endl;
            str.clear();
            l.clear();
            counter = 0;
            level = 8;
        }
        cin>>input;
    }
    return 0;

}



string showExponentSP(int temp, int item)
{
    string s="";
    stringstream ss(s);

    if(item == 0)
    {
        ss<<temp;
    }
    else if(item == 1)
    {
        if (temp == 0)
        {
            ss<<"";
        }
        else
        {
            if(temp == -1)
            ss<<"-x";
            else if(temp == 1)
            ss<<"x";
            else
            ss<<temp<<"x";
        }
    }
    else
    {
        if (temp == 0)
        {
            ss<<"";
        }
        else
        {
            if(temp == -1)
            ss<<"-x^"<<item;
            else if(temp == 1)
            ss<<"x^"<<item;
            else
            ss<<temp<<"x^"<<item;
        }
    }
    return ss.str();
}


string showExponent(int temp, int item)
{
    string s="";
    stringstream ss(s);
    if(item>1)
    {
        if(temp == -1)
        ss<<" - "<<"x^"<<item;
        else if(temp == 1)
        ss<<" + "<<"x^"<<item;
        else if(temp<0)
        ss<<" - "<<(-temp)<<"x^"<<item;
        else if(temp>0)
        ss<<" + "<<temp<<"x^"<<item;
        else
        ss<<"";
    }
    else if(item == 0)
    {
        if(temp<0)
        ss<<" - "<<(-temp);
        else if(temp>0)
        ss<<" + "<<temp;
        else
        ss<<"";
    }else
    {
        if(temp == -1)
        ss<<" - "<<"x";
        else if(temp == 1)
        ss<<" + "<<"x";
        else if(temp<-1)
        ss<<" - "<<(-temp)<<"x";
        else if(temp>1)
        ss<<" + "<<temp<<"x";
        else
        ss<<"";
    }
    //cout<<item<<"  ";
    return ss.str();
}



Sunday, November 7, 2010

ACM-382 Perfection with C++


#include <iostream>
#include <iomanip>
#include <list>

using namespace std;

int sqrts(int test);
void compare(int val, int com);

int main()
{
    int input;
    int result;

    list<int> l;

    cin>>input;
    while(input != 0)
    {
        l.push_back(input);
        cin>>input;
    }

    cout<<"PERFECTION OUTPUT"<<endl;

    list<int>::iterator iter = l.begin();
    while( iter != l.end() ) {
        result = sqrts(*iter);
        compare(*iter, result);
        ++iter;
    }

    cout<<"END OF OUTPUT"<<endl;
    return 0;
}

int sqrts(int test)
{
    int temp = 0;

    for(int i = 1 ; i < test ; i++)
    {
        if(test%i == 0)
        {
            temp = temp + i;
        }
    }
    return temp;
}

void compare(int val, int sum)
{
    if(val > sum)
    cout<<setw(5)<<val<<"  DEFICIENT"<<endl;
    else if(val == sum)
    cout<<setw(5)<<val<<"  PERFECT"<<endl;
    else
    cout<<setw(5)<<val<<"  ABUNDANT"<<endl;
}

Wednesday, September 29, 2010

找因數 with C++


#include <iostream>
#include <sstream>
#include "math.h"
#include <stack>
#include <windows.h>


using namespace std;
void brute(int test);
void sqrts(int test);

int main()
{
    int input;


    cout << "Input a integer" << endl;

    cin>>input;


 LARGE_INTEGER m_liPerfFreq={0};
 QueryPerformanceFrequency(&m_liPerfFreq);
 LARGE_INTEGER m_liPerfStart={0};
 QueryPerformanceCounter(&m_liPerfStart);

    brute(input);

 LARGE_INTEGER liPerfNow={0};
 QueryPerformanceCounter(&liPerfNow);
 long decodeDulation=( ((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000000)/m_liPerfFreq.QuadPart);



 LARGE_INTEGER m_liPerfFreq2={0};
 QueryPerformanceFrequency(&m_liPerfFreq2);
 LARGE_INTEGER m_liPerfStart2={0};
 QueryPerformanceCounter(&m_liPerfStart2);

    sqrts(input);

 LARGE_INTEGER liPerfNow2={0};
 QueryPerformanceCounter(&liPerfNow2);
 long decodeDulation2=( ((liPerfNow2.QuadPart - m_liPerfStart2.QuadPart) * 1000000)/m_liPerfFreq2.QuadPart);



 cout.setf(ios::showpoint, ios::fixed);
 cout.precision (10);

    cout<<decodeDulation<<"  "<<decodeDulation2<<endl;

    return 0;
}


void brute(int test)
{
    string str = "";
    stringstream ss(str);
    for(int i = 1 ; i <= test ; i++)
    {
        if(test%i == 0)
        {
            ss<<i<<"|";
        }
    }
    cout<<ss.str()<<endl;
}



void sqrts(int test)
{
    string str = "";
    stringstream ss(str);
    stack<int> first;

    int temp;
    double sq;

    sq = (int) sqrt(test);

    for(int i = 1 ; i <= sq ; i++)
    {
        if(test%i == 0)
        {
            ss<<i<<"|";
            if(test/i != i)
            {
                first.push(test/i);
            }

        }
    }

    while(!first.empty())
    {
        temp = first.top();
        first.pop();
        ss<<temp<<"|";
    }

    cout<<ss.str()<<endl;
}