Here’s a routine that returns the highest bit number

留下评论

Original: http://groups.google.co.uk/group/comp.lang.c/browse_thread/thread/27bec95613efeed6/6a5983535088d349?q=0x7dcd629#6a5983535088d349

const char clz_table[32] =
  {
    0, 31, 9, 30, 3, 8, 18, 29, 2, 5, 7, 14, 12, 17,
    22, 28, 1, 10, 4, 19, 6, 15, 13, 23, 11, 20, 16,
    24, 21, 25, 26, 27
  };
unsigned long clz(unsigned long n)
  {
    unsigned long c = 0x7dcd629;       /* magic constant… */

    n |= (n >> 1);
    n |= (n >> 2);
    n |= (n >> 4);
    n |= (n >> 8);
    n |= (n >> 16);
    if (n == 0) return 32;
    n = c + (c * n);
    return 31 – clz_table[n >> 27];       /* For little endian    */
  }

Problem C. Sum of Factorials

留下评论

Input file: standard input
Output file: standard output

John von Neumann, b. Dec. 28, 1903, d. Feb. 8, 1957, was a
Hungarian-American mathematician who made important contributions to the
foundations of mathematics, logic, quantum physics, meteorology, science,
computers, and game theory. He was noted for a phenomenal memory and the
speed with which he absorbed ideas and solved problems. In 1925 he received
a B.S. diploma in chemical engineering from Zurich Institute and in 1926 a
Ph.D. in mathematics from the University of Budapest, His Ph.D.
dissertation on set theory was an important contributions to the subject.
At the age of 20, von Neumann proposed a new definition of ordinal numbers
that was universally adopted. While still in his twenties, he made many
contributions in both pure and applied mathematics that established him as
a mathematician of unusual depth. His Mathematical Foundation of Quantum
Mechanics (1932) built a solid framework for the new scientific discipline.
During this time he also proved the mini-max theorem of GAME THEORY. He
gradually expanded his work in game theory, and with coauthor Oskar
Morgenstern he wrote Theory of Games and Economic Behavior (1944).
There are some numbers which can be expressed by the sum of factorials. For
example 9, 9 = 1! + 2! + 3! . Dr. von Neumann was very interested in such
numbers. So, he gives you a number n, and wants you to tell whether or not
the number can be expressed by the sum of some factorials.
Well, it is just a piece of case. For a given n, you will check if there
are some xi, and let n equal to
∑t (上标) i=1(下标) xi! (t≥1, xi≥0, xi = xj <==> i = j)
      t
即  ∑    xi! (t≥1, xi≥0, xi = xj <==> i = j)
      i=1
If the answer is yes, say "YES"; otherwise, print out
"NO".

Input
You will get a non-negative integer n (n≤1,000,000) from input file.

Output
For the n in the input file, you should print exactly one word ("YES" or
"NO") in a single line. No extra spaces are allowed.

Sample input and output
Standard input                      standard output
9                                   YES
2                                   YES

// Since the max input value is 1000000
#define MAX_NUM 10
int _tmain(int argc, _TCHAR* argv[])
{
 unsigned long values[MAX_NUM];
 int i = 1;
 values[i – 1] = 1;
 for (i = 2; i <= MAX_NUM; ++i)
 {
  values[i – 1] = values[i – 2] * i;
 }
 
 unsigned long input = 0;
 cin >> input;
 while (input > 0)
 {
  unsigned long b = 0;
  int start = MAX_NUM – 1;
  int i;
  for (i = start; i >= 0; –i)
  {
   b += values[i];
   if (input < b)
   {
    b -= values[start];
    –start;
    continue;
   }
   else if (input == b)
   {
    cout << "YES" << endl;
    break;
   }
  }
  if (i < 0)
  {
   cout << "NO" << endl;
  }
  cin >> input;
 }
 return 0;
}

24-point Algorithm

留下评论

#include <iostream>
#include <string.h>
using namespace std;

#define NUM 4

int a[NUM];
int b[NUM – 1];
int c[NUM – 2];

string expression;
int count;

typedef enum {
    ADD,
    MINUS, // a – b
    MINUS1, // b – a
    MULTIPLE,
    DEVIDE, // a / b
    DEVIDE1 // b / a
} Operators;

// n <= 19 && n >= 0
void itoa_2bits(int n, char * s)
{
    if (n >= 10) {
        s[0] = ‘1’;
        s[1] = n – 10 + ‘0’;
    } else {
        s[0] = n + ‘0’;
    }
}

int Compute(int operand1, int operand2, Operators oper)
{
    int result;
    switch (oper) {
        case ADD:
        result = operand1 + operand2;
        break;
        case MINUS:
        result = operand1 – operand2;
        break;
        case MULTIPLE:
        result = operand1 * operand2;
        break;
        case DEVIDE:
        result = operand1 / operand2;
        break;
        case MINUS1:
        result = operand2 – operand1;
        case DEVIDE1:
        result = operand2 / operand1;
        break;
        default:
        result = 0;
        break;
    }
    return result;
}

string ConcatString(int operand1, int operand2, Operators oper)
{
    string s;
    s.append("(");

    char n1[3];
    char n2[3];
    memset(n1, 0, sizeof(char) * 2);
    memset(n2, 0, sizeof(char) * 2);
    itoa_2bits(operand1, n1);
    itoa_2bits(operand2, n2);
    switch (oper) {
        case ADD:
        s.append(n1, 3);
        s.append("+");
        s.append(n2, 3);
        break;
        case MINUS:
        s.append(n1, 3);
        s.append("-");
        s.append(n2, 3);
        break;
        case MULTIPLE:
        s.append(n1, 3);
        s.append("*");
        s.append(n2, 3);
        break;
        case DEVIDE:
        s.append(n1, 3);
        s.append("/");
        s.append(n2, 3);
        break;
        case MINUS1:
        s.append(n2, 3);
        s.append("-");
        s.append(n1, 3);
        break;
        case DEVIDE1:
        s.append(n2, 3);
        s.append("/");
        s.append(n1, 3);
        break;
        default:
        break;
    }
    s.append(")");
    return s;
}

void SolutionFor24(int n)
{
    if (n == 2) {
        for (int i = ADD; i <= DEVIDE1; ++i) {
            if (Compute(c[0], c[1], static_cast<Operators>(i)) == 24) {
                ++count;
                expression.append(c[0], c[1], static_cast<Operators>(i));
            }
        }
    } else {
        // 1. choose two numbers and apply six operators to them as the new number in the set;
        // 2. call SolutionFor24(n – 1);
    }
}

int main()
{
    int i;
    while (1) {
        cout << "Please input the four number:" << endl;
        cin >> a[0];
        if (a[0] == 0) {
            break;
        }
        for (i = 1; i < NUM; ++i) {
            cin >> a[i];
        }
        count = 0;
        SolutionFor24(NUM);
    }
    return 0;
}

How to get Post_Order from In_Order and Pre_Order?

留下评论

// PP32.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
using namespace std;

int GetKey(const char & c)
{
    if (c >= ‘a’)
    {
        return (c – ‘a’ + 26);
    }
    else
    {
        return (c – ‘A’);
    }
}

void Post_Order(const char * pre_order, const char * in_order, char * post_order, int len)
{
    int indexes[52];
    int lens[52];
    int newIndexes[52];
 ::memset(indexes, 0, 52 * sizeof(int));
 ::memset(lens, 0, 52 * sizeof(int));
 ::memset(newIndexes, 0, 52 * sizeof(int));
    int i;
    for (i = 0; i < len; ++i)
    {
        indexes[GetKey(in_order[i])] = i;
    }

    lens[GetKey(pre_order[0])] = len;
    post_order[len – 1] = pre_order[0];
    newIndexes[GetKey(pre_order[0])] = len – 1;
 
 int rightLen;
 int leftLen;
 char leftRoot;
 char rightRoot;
 char rightSibling;
    for (i = 0; i < len; ++i)
    {
  if (lens[GetKey(pre_order[i])] == 1)
  {
   continue;
  }
  rightLen = 0;
  if (i != 0)
  {
   char parent;
   if (((GetKey(pre_order[i]) + 1) < len) && (post_order[newIndexes[GetKey(pre_order[i])] + 1] != 0))
   {
    // The current node is the right child root. And the right of it in the post_order is its parent or direct sibling.
    parent = post_order[newIndexes[GetKey(pre_order[i])] + 1];
    if (parent == rightSibling)
    {
     parent = pre_order[i – 1];
    }
   }
   else
   {
    // The current node is the left child root. And the left of it in the pre_order is its parent.
    parent = pre_order[i – 1];
   }

   int relative = indexes[GetKey(parent)] – indexes[GetKey(pre_order[i])];
   if (relative > 0)
   {
    rightLen = relative – 1;
    leftLen = lens[GetKey(pre_order[i])] – rightLen – 1;
   }
   else
   {
    leftLen = -relative – 1;
    rightLen = lens[GetKey(pre_order[i])] – leftLen – 1;
   }
  }
  else
  {
   rightLen = lens[GetKey(pre_order[i])] – indexes[GetKey(pre_order[i])] – 1;
   leftLen = lens[GetKey(pre_order[i])] – rightLen – 1;
  }
  if (leftLen > 0)
  {
         leftRoot = pre_order[i + 1];
         lens[GetKey(leftRoot)] = leftLen;
         post_order[newIndexes[GetKey(pre_order[i])] – rightLen – 1] = leftRoot;
   newIndexes[GetKey(leftRoot)] = newIndexes[GetKey(pre_order[i])] – rightLen – 1;
  }
  if (rightLen > 0)
  {
         rightRoot = pre_order[i + leftLen + 1];
         lens[GetKey(rightRoot)] = rightLen;
         post_order[newIndexes[GetKey(pre_order[i])] – 1] = rightRoot;
   newIndexes[GetKey(rightRoot)] = newIndexes[GetKey(pre_order[i])] – 1;
   rightSibling = rightRoot;
  }
  else
  {
   rightSibling = 0;
  }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
 
 char * res = new char[3];

 ::memset(res, 0, 3 * sizeof(char));
 ::Post_Order("ABC", "BAC", res, 3);
 cout << "Expected: " << "BCA" << endl;
 cout << "The actual post_order is :" << res << endl;

 ::memset(res, 0, 3 * sizeof(char));
 ::Post_Order("ABC", "CBA", res, 3);
 cout << "Expected: " << "CBA" << endl;
 cout << "The actual post_order is :" << res << endl;

 ::memset(res, 0, 3 * sizeof(char));
 ::Post_Order("ABC", "BCA", res, 3);
 cout << "Expected: " << "CBA" << endl;
 cout << "The actual post_order is :" << res << endl;
 
 ::memset(res, 0, 3 * sizeof(char));
 ::Post_Order("ABC", "ACB", res, 3);
 cout << "Expected: " << "CBA" << endl;
 cout << "The actual post_order is :" << res << endl;

 ::memset(res, 0, 3 * sizeof(char));
 ::Post_Order("ABC", "ABC", res, 3);
 cout << "Expected: " << "CBA" << endl;
 cout << "The actual post_order is :" << res << endl;
 
 delete[] res;

 char * res1 = new char[4];
 ::memset(res1, 0, 4 * sizeof(char));
 ::Post_Order("ABCD", "DCBA", res1, 4);
 cout << "Expected: " << "DCBA" << endl;
 cout << "The actual post_order is :" << res1 << endl;
 
 ::memset(res1, 0, 4 * sizeof(char));
 ::Post_Order("ABCD", "CDBA", res1, 4);
 cout << "Expected: " << "DCBA" << endl;
 cout << "The actual post_order is :" << res1 << endl;
 
 ::memset(res1, 0, 4 * sizeof(char));
 ::Post_Order("ABCD", "CBAD", res1, 4);
 cout << "Expected: " << "CBDA" << endl;
 cout << "The actual post_order is :" << res1 << endl;
 
 ::memset(res1, 0, 4 * sizeof(char));
 ::Post_Order("ABCD", "BCAD", res1, 4);
 cout << "Expected: " << "CBDA" << endl;
 cout << "The actual post_order is :" << res1 << endl;
 
 ::memset(res1, 0, 4 * sizeof(char));
 ::Post_Order("ABCD", "BADC", res1, 4);
 cout << "Expected: " << "BDCA" << endl;
 cout << "The actual post_order is :" << res1 << endl;

 ::memset(res1, 0, 4 * sizeof(char));
 ::Post_Order("ABCD", "BACD", res1, 4);
 cout << "Expected: " << "BDCA" << endl;
 cout << "The actual post_order is :" << res1 << endl;
 
 ::memset(res1, 0, 4 * sizeof(char));
 ::Post_Order("ABCD", "ABCD", res1, 4);
 cout << "Expected: " << "DCBA" << endl;
 cout << "The actual post_order is :" << res1 << endl;
 delete[] res1;
 
 char * res2 = new char[15];
 ::memset(res2, 0, 15 * sizeof(char));
 ::Post_Order("ABCDEFGHIKLNMJ", "DCFEBGAHNLKMIJ", res2, 14);
 cout << "Expected: " << "DFECGBNLMKJIHA" << endl;
 cout << "The actual post_order is :" << res2 << endl;
 delete[] res2;

 char * res3 = new char[7];
 ::memset(res3, 0, 7 * sizeof(char));
 ::Post_Order("ABCDEF", "CBAEDF", res3, 6);
 cout << "Expected: " << "CBEFDA" << endl;
 cout << "The actual post_order is: " << res3 << endl;
 delete[] res3;

 
 char * res4 = new char[4];
 ::memset(res3, 0, 4 * sizeof(char));
 ::Post_Order("xYz", "Yxz", res4, 3);
 cout << "Expected: " << "Yzx" << endl;
 cout << "The actual post_order is: " << res4 << endl;
 delete[] res4;

 
  return 0;
}

(续)Return the first non-repeatable character in a literal string.

留下评论

void Exchange(int a[], int i, int j)
{
 char temp = a[i];
 a[i] = a[j];
 a[j] = temp;
}
void GetFirstOne(char a[], int len)
{
 int perf = 0;
 int * b = new int[len];
 int i;
 for (i = 0; i < len; ++i)
 {
  b[i] = i;
 }

 int *c = new int[len];
 int cLen = 0;

 int start = 0;
 int end = len – 1;

 bool isFound;
 int pos = 0;
 while (pos < len)
 {
  isFound = false;
  for (i = 0; i < cLen; ++i)
  {++perf;
   if (a[b[c[i]]] == a[pos])
   {
    isFound = true;
    break;
   }
   else if (a[b[c[i]]] < a[pos])
   {
    if (i > 0)
    {
     start = c[i – 1] + 1;
    }
    else
    {
     start = 0;
    }
    end = c[i] – 1;
    break;
   }
  }
  if (!isFound)
  {
   if (cLen != 0 && i == cLen)
   {
    start = ((c[i – 1] + 1) > (pos + 1)) ? (c[i – 1] + 1) : (pos + 1);
    end = len – 1;
   }
   int pivot;
   while (start <= end)
   {++perf;
    // DESC
    while (start <= end && a[b[start]] >= a[pos])
    {++perf;
     if (a[b[start]] == a[pos])
     {
      if (b[start] != pos)
      {
       isFound = true;
      }
      break;
     }
     ++start;
    }
    while (end >= start && a[b[end]] <= a[pos])
    {++perf;
     if (a[b[end]] == a[pos])
     {
      if (b[end] != pos)
      {
       isFound = true;
      }
      else
      {
       pivot = end;
      }
     }
     –end;
    }
    if (start <= end)
    {
     Exchange(b, start, end);
    }
   }
   Exchange(b, pivot, end + 1);

   if (!isFound)
   { 
    cout << endl << "perf = " << perf << endl;
    cout << "The wanted char is: " << a[pos] << endl;
    cout << "+++++++++++++++++++++++++++++++" << endl;
    return;
   }   

   int temp = 0;
   while (temp < cLen && c[temp] < (end + 1))
   {
    ++temp;
   }
   if (temp == cLen)
   {
    c[temp] = end + 1;
    ++cLen;
   }
   else
   {
    for (i = cLen; i> temp; –i)
    {
     c[i] = c[i – 1];
    }
    c[temp] = end + 1;
    ++cLen;
   }
  }    
  ++pos;
 }
 delete[] b;
 delete[] c;
}

Return the first non-repeatable character in a literal string.

留下评论

#include <iostream>

using namespace std;

typedef struct ABC
{
    int index;
    int count;
} ABC;

void GetTheFirst(char a[], int len)
{
    if (len == 0)
    {
        return;
    }

    ABC *b = new ABC[len];
    int bLen = 1;
    b[0].index = 0;
    b[0].count = 1;

    int perf = 0;
    for (int i = 1; i < len; ++i)
    {
        int start = 0;
        int end = bLen – 1;
        int pos = 0;
        bool isFound = false;
        while (start <= end)
        {
            ++perf;
            pos = ((start + end) / 2);
            if (a[b[pos].index] == a[i])
            {
                isFound = true;
                b[pos].index = i;
                ++(b[pos].count);
                break;
            }
            else if (a[b[pos].index] > a[i])
            {
                start = pos + 1;
            }
            else
            {
                end = pos – 1;
            }
        }
        if (!isFound)
        {
            ++bLen;
            int temp = bLen – 1;
            while (temp >= start)
            {
                b[temp + 1] = b[temp];
                –temp;
            }
            b[start].index = i;
            b[start].count = 1;
        }
    }

    cout << endl;

    int index = len – 1;
    for (int i = 0; i < bLen; ++i)
    {
        cout << b[i].index << " " << a[b[i].index] << " " << b[i].count << endl;
        if (b[i].count == 1 && index > b[i].index)
        {
            index = b[i].index;
        }
    }

    delete[] b;
    cout << "+++++++++++++++++++++++++++++++" << endl;
    cout << "len = " << len << endl;
    cout << "perf = " << perf + bLen << endl;
    cout << "index = " << index << endl;
    cout << endl;
}

void GetTheFirst1(char a[], int len)
{
    int perf = 0;
    bool *b = new bool[len];
    for (int i = 0; i < len; ++i)
    {
        b[i] = true;
    }
    for (int i = 0; i < len; ++i)
    {
        if (b[i])
        {
            int j;
            bool isFound = false;
            for (j = i + 1; j < len; ++j)
            {
                ++perf;
                if (a[i] == a[j])
                {
                    b[j] = false;
                    isFound = true;
                }
            }
            if (!isFound)
            {
                cout << "perf = " << perf << endl;
                cout << "index = " << i << endl;
                cout << endl;
                break;
            }
        }
    }
    delete[] b;
}

void GetTheFirst2(char a[], int len)
{
    int perf;
    for (int i = 0; i < len; ++i)
    {
        int j;
        for (j = 0; j < len; ++j)
        {
            ++perf;
            if (i != j && a[i] == a[j])
            {
                break;
            }
        }
        if (j == len)
        {
            cout << "perf = " << perf << endl;
            cout << "index = " << i << endl;
            cout << "+++++++++++++++++++++++++++++++" << endl << endl;
            break;
        }
    }
}

int main()
{
    char a[] = "ab1cdedaacb1ddddep";
    GetTheFirst(a, sizeof(a) – 1);
    GetTheFirst1(a, sizeof(a) – 1);
    GetTheFirst2(a, sizeof(a) – 1);

    char b[] = "qab1cdedaacb1ddddep";
    GetTheFirst(b, sizeof(b) – 1);
    GetTheFirst1(b, sizeof(b) – 1);
    GetTheFirst2(b, sizeof(b) – 1);

    char c[] = "ab1cdedaacb1ddddepefqacf";
    GetTheFirst(c, sizeof(c) – 1);
    GetTheFirst1(c, sizeof(c) – 1);
    GetTheFirst2(c, sizeof(c) – 1);

    char d[] = "jli,.kjiunkgajfi1294423n423nnsjwidjsjab1cdedaacb1ddddepefqacfasdffesdcdesdssejli,.kjiunkgajfi1294423n423nnsjwidjsj";
    GetTheFirst(d, sizeof(d) – 1);
    GetTheFirst1(d, sizeof(d) – 1);
    GetTheFirst2(d, sizeof(d) – 1);

    char e[] = "0123456789abcdefghijhlmnopqrstuvwxyz";
    GetTheFirst(e, sizeof(e) – 1);
    GetTheFirst1(e, sizeof(e) – 1);
    GetTheFirst2(e, sizeof(e) – 1);

    char f[] = "zyxwvutsrqponmlhjihgfedcba9876543210";
    GetTheFirst(f, sizeof(f) – 1);
    GetTheFirst1(f, sizeof(f) – 1);
    GetTheFirst2(f, sizeof(f) – 1);
    return 0;
}

排列算法

留下评论

#include <iostream>
using namespace std;

#define N 5
#define M 2
int data[] = {1, 2, 3, 4, 5};
int len = N;
int count = 0;

void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

void permutation(int* arr, int n, int m)
{
    int i;
    if (m == 0)
    {
        ++count;
        for (i = 0; i < M; ++i)
        {
            cout << data[i] << " ";
        }
        cout << endl;
        return;
    }
    for (i = 0; i < n; ++i)
    {
        swap(arr[i], arr[0]);
        permutation(arr + 1, n – 1, m – 1);
        swap(arr[i], arr[0]);
    }
}

Older Entries