2013年8月30日 星期五

bridge and torch (not optimal solution)


#include <iostream>
#include <algorithm>
using namespace std;
void sol1();
 
void print_array(int *A, int n){
 cout << "{ ";
 for(int i=0;i<n;i++){
  cout << A[i] << ' ';
 }
 cout << '}';
}
void print_status(int *A, int n, int *B, int m, int cost){
 cout << endl;
 print_array(A,n);
 print_array(B,m);
 cout << ":" << cost;
 cout << endl;
}
void sol2(){
  int n;
 cin >> n;
 int *A= new int[n]; 
 int *B=A+n;
 int m=0;
 int cost=0;
 
 for(int i=0;i<n;i++){
  cin >> A[i];
 }
 
 if (n<=0){
  cout << "n must be larger than 0";
  system("pause");
  return ;
 }else if(n==1){
  cout << "cost:" << A[0];
  system("pause");
  return ;
 }else if(n==2){
  cout << "cost:" << max(A[0],A[1]);
  system("pause");
  return ;
 }
 
 sort(A,A+n);
 print_status(A,n,B,m,cost);
 
 while(n>0){
  //GO 
  B--;B--;
  cost+=A[n-1];
  swap(A[0],B[0]);
  n-=2;m+=2; 
  print_status(A,n,B,m,cost);
  //BACK
  if (n>0){
   cost+=B[0];//寫錯的地方
   swap(A[0],B[0]);
   B++;
   n++;m--; 
   print_status(A,n,B,m,cost);
  }
 }
 
 cout << "cost:" << cost << endl;
}
int main()
{
 //sol1();
 sol2();
 system("pause");
    
    return 0;
}
// SOURCE: http://hoyusun.blogspot.tw/2012/02/blog-post.html
void sol1(){
 int n;
 cin >> n;
 int *A= new int[n];  
 for(int i=0;i<n;i++){
  cin >> A[i];
 }
    
 int cost = 0;
    sort(A, A+n);
    for(n--; n >= 3; n -= 2){   
        int t1 = A[1] + A[0] + A[n] + A[1];  //AB->A->CD->B, 故B+A+D+B
        int t2 = A[n] + A[0] + A[n-1] + A[0];   //AD->A->AC->A, 故D+A+C+A
        cost += t1<t2?t1:t2; //取最小時間
    }
    if(n == 2)  cost += (A[2]+A[0]+A[1]);    //若三個人時, AC->A->AB故C+A+B
    else if(n == 1) cost += A[1];   //若兩個人時, AB故B
    else    cost += A[0];     //只有一個人, A故A
    cout << cost << endl;
}

2013年8月17日 星期六

Array and Pointer

2D Array

Array

Pointer



Diamond

#include <iostream>
#include <string>
using namespace std;
void method1(){ 
 int n;
 cin >> n; 
 
 //being: init char string a
 char *a = new char[2*n]; 
 for (int i=0;i<2*n-1;i++){
  a[i]=' ';
 }
 a[2*n-1]='\0';
 //end: init char string a
 
 for (int i=0;i<=n-1;i++){    
     a[n-i-1]='A';
     a[n+i-1]='A';  
  cout << a << endl;
 }
 
 for (int i=n-1;i>=0;i--){    
     a[n-i-1]=' ';
     a[n+i-1]=' ';  
  cout << a << endl;
 }
}
 
void method2(){
 int n;
 cin >> n; 
 
 string a=string(2*n,' '); //init string a
 
 for (int i=0;i<=n-1;i++){    
     a[n-i-1]='A';
     a[n+i-1]='A';  
  cout << a << endl;
 }
 
 for (int i=n-1;i>=0;i--){    
     a[n-i-1]=' ';
     a[n+i-1]=' ';  
  cout << a << endl;
 }
}
int main(){ 
 method2();
 system("pause");
}