查看: 13795| 回复: 25
跳转到指定楼层
上一主题 下一主题
收起左侧

Stanford Design and Analysis of Algorithm I 第二期 Week#6 自由讨论

全局:
公开课
学校名称: Stanford
Unit号: 6
开课时间: 2012-07-16
课程全名: Stanford Design and Analysis of Algorithm I
平台: Coursera

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
SUMMARY: This week wraps up our discussion of data structures. We'll discuss three different data structures, all of which are widely used in practice. As usual, the primary goal is to understand what these data structures are good for and the trade-offs between them, but we'll also spend some time talking about what's "under the hood." First, we have several more videos about hash tables. The first one is required and finally discusses what we mean by "pathological data sets" for hash functions. The next three videos are optional but they cover great stuff --- how randomization dodges pathological data sets, a construction of simple hash functions that are guaranteed to (in expectation over the choice of a random hash function) spread every data set out evenly, and performance analyses of hashing with both chaining and open addressing. Second, there are two required videos on the implementation and performance of bloom filters, which are like hash tables except that they are insanely space-efficient and occasionally suffer from false positives. We conclude with a series of videos on balanced binary search trees --- a data structure that is dynamic (accommodating insertions and deletions) while supporting a rich set of operations that all run in logarithmic time.

THE HOMEWORK: Problem Set 6 should solidify your understanding of hash tables and search trees. In the programming project you'll implement two slick data structure applications that we saw back in Week 5 (the 2-SUM problem via hash tables, and median maintenance via heaps).

点评

烦请各位注意公开课的honor code,不要随意分享代码。可以用白色字体隐藏哈~~  发表于 2013-8-20 15:08

上一篇:[Udacity CS215 Algorithm] 问个HW4计算中位数的题
下一篇:Stanford CS106A(programming methodology)报名贴
推荐
果果达人 2014-11-18 19:25:03 | 只看该作者
全局:
shidaohang 发表于 2012-7-25 09:47
本周两道编程题都很简单
Problem 6-1 Two-Sum via HashProblem 6-2 Median via Heap
题目不难,于是我尝 ...

怎么运行你的代码?没有反应啊question1的
回复

使用道具 举报

🔗
 楼主| shidaohang 2012-7-25 09:47:51 | 只看该作者
全局:
本周两道编程题都很简单
Problem 6-1 Two-Sum via Hash
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<ctype.h>
  4. const char INFILE[] = "HashInt.txt";
  5. #define MAX        10000000

  6. void fetch_hash(long *hash)        {
  7.   FILE *fp = fopen(INFILE,"r");
  8.   char line[10];
  9.   long i;
  10.   for (i=0; i<MAX; i++)
  11.         hash[i] = 0;
  12.   while (fgets(line,10,fp))
  13.         hash[atoi(line)] ++;
  14. }
  15. short two_sum(long *hash, long t)        {
  16.   long x;
  17.   for (x = 1; x < (t-1)/2; x++)       
  18.         if ((hash[x])&&(hash[t-x]))
  19.           return 1;
  20.   return 0;
  21. }

  22. void main()
  23. {
  24.   long *hash = calloc(MAX,sizeof(long));
  25.   fetch_hash(hash);
  26.   short i,count = 0;
  27.   for (i = 2500; i <= 4000; i++)
  28.         if (two_sum(hash,i))
  29.           count++;
  30.   printf("count = %d\n",count);
  31. }
复制代码
Problem 6-2 Median via Heap
题目不难,于是我尝试了下调用自定义的头函数"heap.h",里面存放了所有的heap函数
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<ctype.h>
  4. #include"heap.h"
  5. const char INFILE[] = "Median.txt";
  6. #define MAX        10000

  7. short RETURN_MEDIAN(short *A1,short *A2,short x)        {
  8.   if (x<A2[1])
  9.         MAX_HEAP_INSERT(A1,x);
  10.   else
  11.         MIN_HEAP_INSERT(A2,x);
  12.   if (A1[0]-A2[0]>1)       
  13.         MIN_HEAP_INSERT(A2,EXTRACT_MAX(A1));
  14.   if (A2[0]>A1[0])       
  15.         MAX_HEAP_INSERT(A1,EXTRACT_MIN(A2));
  16.   return A1[1];
  17. }
  18. void print(short *A)        {
  19.   short i;
  20.   for (i=1; i<=A[0]; i++)
  21.         printf("%d ",A[i]);
  22. }

  23. void main()        {
  24.   short *A1,*A2,m=0;
  25.   A1 = calloc(1+MAX,sizeof(short));
  26.   A2 = calloc(1+MAX,sizeof(short));
  27.   A1[0] = 1; A1[1] = 0;
  28.   A2[0] = 1; A2[1] = 20000;
  29.   char line[10];
  30.   FILE *fp = fopen(INFILE,"r");
  31.   while (fgets(line,10,fp))       
  32.         m = (m + RETURN_MEDIAN(A1,A2,atoi(line))) % 10000;
  33.   printf("%d\n",m);
  34. }
复制代码
其中heap.h的代码就是所有的heap函数
  1. #ifndef _HEAP_H_
  2. #define _HEAP_H_
  3. //        MAX_HEAP
  4. void MAX_HEAPIFY(short *A,short i)        {
  5.         short left=2*i,right=2*i+1,larger,tmp;
  6.         if ((left<=A[0])&&(A[left]>A[i]))
  7.           larger = left;
  8.         else
  9.           larger = i;
  10.         if ((right<=A[0])&&(A[right]>A[larger]))
  11.           larger = right;
  12.         if (larger != i)        {
  13.           tmp = A[larger]; A[larger] = A[i]; A[i] = tmp;
  14.           MAX_HEAPIFY(A,larger);
  15.         }
  16. }
  17. short EXTRACT_MAX(short *A)        {
  18.   short max = A[1];
  19.   A[1] = A[A[0]--];
  20.   MAX_HEAPIFY(A,1);
  21.   return max;
  22. }
  23. void HEAP_INCREASE_KEY(short *A,short i,short key)        {
  24.   short tmp;
  25.   A[i] = key;
  26.   while ((i>1)&&(A[i/2]<A[i]))        {
  27.         tmp = A[i]; A[i] = A[i/2]; A[i/2] = tmp;
  28.         i = i/2;
  29.   }
  30. }
  31. void MAX_HEAP_INSERT(short *A,short key)        {
  32.   A[0]++;
  33.   HEAP_INCREASE_KEY(A,A[0],key);
  34. }
  35. //        MIN_HEAP
  36. void MIN_HEAPIFY(short *A,short i)        {
  37.         short left=2*i,right=2*i+1,smaller,tmp;
  38.         if ((left<=A[0])&&(A[left]<A[i]))
  39.           smaller = left;
  40.         else
  41.           smaller = i;
  42.         if ((right<=A[0])&&(A[right]<A[smaller]))
  43.           smaller = right;
  44.         if (smaller != i)        {
  45.           tmp = A[smaller]; A[smaller] = A[i]; A[i] = tmp;
  46.           MIN_HEAPIFY(A,smaller);
  47.         }
  48. }
  49. short EXTRACT_MIN(short *A)        {
  50.   short min = A[1];
  51.   A[1] = A[A[0]--];
  52.   MIN_HEAPIFY(A,1);
  53.   return min;
  54. }
  55. void HEAP_DECREASE_KEY(short *A,short i,short key)        {
  56.   short tmp;
  57.   A[i] = key;
  58.   while ((i>1)&&(A[i/2]>A[i]))        {
  59.         tmp = A[i]; A[i] = A[i/2]; A[i/2] = tmp;
  60.         i = i/2;
  61.   }
  62. }
  63. void MIN_HEAP_INSERT(short *A,short key)        {
  64.   A[0]++;
  65.   HEAP_DECREASE_KEY(A,A[0],key);
  66. }
  67. #endif
复制代码
回复

使用道具 举报

🔗
steveneo 2012-7-26 00:08:32 | 只看该作者
全局:
第一题的代码,发现一个点,因为题目要求t属于 [2500,4000]范围内,所以x + y = t, x,y 必然也是4000内的整数,那这个哈希函数的范围只要4000个slot就够了。我看HashInt.txt文件里还有几十万个数,有的数字有8million这么大,其实都可以忽略掉的。只要4000以内的数就够了
  1. #include <iostream>
  2. #include <fstream>
  3. #define MIN 4000
  4. using namespace std;

  5. int hash[MIN + 1] = { 0 };
  6. int count = 0;

  7. void readData() {
  8. ifstream fin("HashInt.txt");
  9. int temp = 0;
  10. while(fin>>temp) {
  11. if(temp < MIN) hash[temp]++;
  12. }
  13. }

  14. bool hashMap(int n) {
  15. if(n > MIN) return false;
  16. if(hash[n]) return true;
  17. else return false;
  18. }

  19. int main() {
  20. readData();

  21. for(int i = 2500; i <= 4000; i++) {
  22. for(int j = 1; j <= (i - 1) / 2; j++) {
  23. if(hashMap(j) && hashMap(i - j)) {
  24. count++;
  25. break;
  26. }
  27. }
  28. }

  29. cout<<count<<endl;
  30. return 0;
  31. }
复制代码

第二题的搞了一下午+晚上了,还是不行,最后的结果有问题啊,请大家看看我这代码怎么错误了,多谢多谢了。我把main.cpp贴出来
  1. #include <iostream>
  2. #include <vector>
  3. #include <fstream>
  4. #include "heap.h"
  5. using namespace std;

  6. int main() {
  7. ifstream fin("Median.txt");

  8. MaxHeap maxh;
  9. MinHeap minh;
  10. int medianSum = 0;
  11. int temp;

  12. while(fin>>temp) {
  13. if(temp < maxh.top()) {
  14. if(maxh.heapSize() <= minh.heapSize()) maxh.insert(temp);
  15. else if(maxh.heapSize() == minh.heapSize() + 1) {
  16. maxh.insert(temp);
  17. int shift = maxh.extractMax();
  18. minh.insert(shift);
  19. }
  20. }

  21. if(temp >= maxh.top() && temp <= minh.top()) {
  22. if(maxh.heapSize() <= minh.heapSize()) maxh.insert(temp);
  23. else minh.insert(temp);
  24. }

  25. if(temp > minh.top()) {
  26. if(minh.heapSize() <= maxh.heapSize()) minh.insert(temp);
  27. else if(minh.heapSize() == maxh.heapSize() + 1) {
  28. minh.insert(temp);
  29. int shift = minh.extractMin();
  30. maxh.insert(shift);
  31. }
  32. }

  33. //median add
  34. if(maxh.heapSize() >= minh.heapSize()) medianSum += maxh.top();
  35. if(maxh.heapSize() < minh.heapSize()) medianSum += minh.top();
  36. }

  37. cout<<medianSum % 10000<<endl;
  38. return 0;
  39. }
复制代码


如果大家觉得上面main.cpp没错,可能就是我自己写的heap.h有问题了……


回复

使用道具 举报

🔗
frankuz 2012-7-26 15:51:02 | 只看该作者
全局:
  1. hash = {}
  2. count = 0
  3. input_file = open('HashInt.txt')
  4. for line in input_file:
  5.         num = int(line.rstrip('\n'))
  6.         hash[num] = 1
  7. input_file.close()
  8.                
  9. def target_sum (t):
  10.         for element in hash:
  11.                 t_el = t-element
  12.                 if t_el in hash and t_el != element:
  13.                         return 1
  14.         return 0

  15. for i in range(2500,4001):
  16.         if target_sum(i):
  17.                 count += 1
  18. print count
复制代码
回复

使用道具 举报

全局:
本帖最后由 蜡笔小丸子 于 2012-7-27 02:39 编辑

第一题遍历x时,如果用课上讲的theta(N)的算法,会出现pair(x,y) 的重复。所以此处取x=(1,sum/2)可以避免重复。
  1. #include <iostream>
  2. #include <fstream>
  3. #include <list>
  4. #include <string>

  5. using namespace std;

  6. #define LIST_SIZE 500000
  7. #define MIN_SUM 2500
  8. #define MAX_SUM 4000

  9. class HashTable{
  10. private:
  11.         bool hash_table[MAX_SUM];
  12. public:
  13.         HashTable(){
  14.                 memset(hash_table,false,sizeof(hash_table));
  15.         }

  16.         unsigned int GetHashValue(unsigned int key){
  17.                 if (key<MAX_SUM) return key;
  18.                 else return 0;
  19.         }

  20.         void Insert(unsigned int key){
  21.                 hash_table[GetHashValue(key)] = true;
  22.         }

  23.         bool LookUp(unsigned int key){
  24.                 return hash_table[GetHashValue(key)];
  25.         }
  26. };


  27. int main(){
  28.         fstream file("HashInt.txt");
  29.         unsigned int myarray[LIST_SIZE];
  30.         HashTable mytable;
  31.         if (!file.is_open()) cerr<<"Error opening file!"<<endl;
  32.         else{
  33.                 for (size_t i=0;i<LIST_SIZE; i++){
  34.                         file>>myarray[i];
  35.                         mytable.Insert(myarray[i]);  //insert elements of A into hash table. Theta(n), n = LIST_SIZE
  36.                 }
  37.         }
  38.         file.close();

  39.         int count=0;
  40.         for (int t =MIN_SUM;t <= MAX_SUM; t++)
  41.                 //for (size_t x = 0; x<LIST_SIZE;x++){ // for each x in A, look up y = sum -x in hash table. Theta(n)
  42.                 for (int x=1;x< t/2;x++){  //ensure that x != y
  43.                         if (mytable.LookUp(x) && mytable.LookUp(t-x))
  44.                         {  
  45.                                 count++;        
  46.                                 break;}
  47.                 }
  48.         cout<<"Number of existing t = "<<count<<endl;
  49.         
  50.         return 0;
  51. }
复制代码
  1. #include <iostream>
  2. #include <fstream>
  3. #include <algorithm>
  4. #include <stdexcept>
  5. using namespace std;

  6. #define SIZE 10000
  7. #define HALF_SIZE 5000

  8. class MaxHeap{
  9. public:
  10.         MaxHeap():size_maxheap(0){ memset(maxHeap,0,sizeof(maxHeap));}
  11.         size_t getSize(){ return size_maxheap;}
  12.         unsigned int getMax(){return maxHeap[0];}
  13.         void Insert(unsigned int keyValue){
  14.           // CODE for heap insertion here
  15.         }
  16.         unsigned int ExtractMax(){
  17.                 // CODE for extract-max here
  18.         }
  19. private:
  20.         //void setSize(size_t size){ heap_size = size; return;}
  21.         unsigned int maxHeap[HALF_SIZE];
  22.         size_t size_maxheap;
  23. };

  24. class MinHeap{
  25. public:
  26.         MinHeap():size_minheap(0){ memset(minHeap,0,sizeof(minHeap));}
  27.         size_t getSize(){ return size_minheap;}
  28.         unsigned int getMin(){return minHeap[0];}
  29.         void Insert(unsigned int keyValue){
  30. // CODE for heap insertion here
  31.          }
  32.         unsigned int ExtractMin(){
  33.                //CODE for extract-min here
  34.         }
  35. private:
  36.         //void setSize(size_t size){ heap_size = size; return;}
  37.         unsigned int minHeap[HALF_SIZE];
  38.         size_t size_minheap;
  39. };


  40. int main(){
  41.         MinHeap Hhigh;
  42.         MaxHeap Hlow;
  43.         unsigned int median=0;
  44.   
  45.         fstream file("Median.txt");
  46.         if (!file.is_open()) cerr<<"Error reading file."<<endl;
  47.         else{
  48.                 unsigned int extra1,extra2;
  49.                 while (!file.eof()){
  50.                         file>>extra1;
  51.                         // odd node, maintain max(Hlow)<extra1<min(Hhigh),extra1 would become the median
  52.                         if (extra1 < Hlow.getMax()){
  53.                                 Hlow.Insert(extra1);
  54.                                 extra1 = Hlow.ExtractMax();}
  55.                         else if (extra1 > Hhigh.getMin()){
  56.                                 Hhigh.Insert(extra1);
  57.                                 extra1 = Hhigh.ExtractMin();}
  58.                         median += extra1;
  59.                         // even node, insert extra1 and extra2 into Hlow and Hhigh. max(Hlow) would become the median
  60.                         file>>extra2;
  61.                         if (extra2 > extra1) {
  62.                                 Hlow.Insert(extra1);
  63.                                 Hhigh.Insert(extra2);}
  64.                         else {
  65.                                 Hlow.Insert(extra2);
  66.                                 Hhigh.Insert(extra1);}
  67.                         median += Hlow.getMax();
  68.                 }
  69.         }
  70.         cout<<median%10000<<endl;
  71.         return 0;
  72. }
复制代码
回复

使用道具 举报

🔗
asterid 2012-7-27 06:47:42 | 只看该作者
全局:
本帖最后由 asterid 于 2012-7-27 07:12 编辑

第一题用Python里的字典更好,不过我用的是list……
  1. #hash by mod of 500009
  2. def fhash(n):
  3.     return n % 500009

  4. def read_file(filename):
  5.     l_input=[]
  6.     myfile = open(filename)
  7.     print 'file open'
  8.     for line in myfile:
  9.         num = int(line.rstrip('\n'))
  10.         l_input.append(num)
  11.     myfile.close()
  12.     print 'file closed'
  13.     return l_input

  14. def input_to_hash(l_input):
  15.     l_hash=[]
  16.     while len(l_hash) < (500009+10):
  17.         l_hash.append([])
  18.     print 'hashing initiated'
  19.     n=len(l_input)
  20.     for i in range (0,n):
  21.         l_hash[fhash(l_input[i])].append(l_input[i])
  22.     print 'hashing finished'
  23.     return l_hash

  24. l_hash = input_to_hash(read_file('E://HashInt.txt'))
  25. two_sum=[]
  26. for i1 in range(2500,4001):
  27.     for i2 in range (1, i1 / 2):
  28.         if i2 in l_hash[fhash(i2)] and (i1 - i2) != i2 and (i1 - i2) in l_hash[fhash(i1 - i2)]:
  29.             two_sum.append([i1,i2,i1-i2])
  30.             #print i1, '=', i2, '+', i1 - i2, 'in', l_hash[fhash(i2)], 'and', l_hash[fhash(i1 - i2)]
  31.             break
  32. print 'answer:',len(two_sum)
复制代码
这一题还是用list(sorted array)实现的,把每一行的数字(O(n))用二分法插入一个已排序的array(O(logn)),插入式保持有序。最终的时间复杂度应该是 O(nlogn)。
  1. def read_file(filename):
  2.     l_input = []
  3.     myfile = open(filename)
  4.     print 'file open'
  5.     for line in myfile:
  6.         num = int(line.rstrip('\n'))
  7.         l_input.append(num)
  8.     myfile.close()
  9.     print 'file closed'
  10.     return l_input

  11. def get_median(k1, k2):
  12.     if (k1 + k2) % 2 != 0: return (k1 + k2 - 1) / 2
  13.     else: return (k1 + k2) / 2
  14.    
  15. def sort_insert(e, slist):
  16.     n = len(slist)
  17.     if n == 0:
  18.         slist.append(e)
  19.     else:
  20.         k1 = 1
  21.         k2 = n
  22.         k = get_median(k1, k2)
  23.         while k2 - k1 > 1:
  24.             if e >= slist[k-1]: k1 = k
  25.             elif e < slist[k-1]: k2 = k
  26.             k = get_median(k1, k2)
  27.         if k1 == k2:            
  28.             if e >= slist[k-1]: slist.insert(k, e)
  29.             else: slist.insert(k-1, e)
  30.         elif k2 == k1 +1:
  31.             if e <= slist[k1-1]: slist.insert(k1-1, e)
  32.             elif e >= slist[k2-1]: slist.insert(k2, e)
  33.             elif e <= slist[k-1]: slist.insert(k-1, e)
  34.             elif e > slist[k-1]: slist.insert(k2-1, e)
  35.     return slist

  36. def sort_median(mylist):
  37.     slist = []
  38.     medianlist = []
  39.     n = len(mylist)
  40.     for i in range (0, n):
  41.         sort_insert(mylist[i],slist)
  42.         medianlist.append(slist[get_median(0,len(slist)-1)])               
  43.     return medianlist

  44. myfile = 'E://Median.txt'
  45. mylist = read_file(myfile)
  46. medianlist=sort_median(mylist)
  47. print 'answer:', sum(medianlist) % 10000
复制代码
回复

使用道具 举报

🔗
smgjzh 2012-7-27 13:37:34 | 只看该作者
全局:
有没有人讨论理论题?
回复

使用道具 举报

🔗
endless 2012-7-27 17:13:23 | 只看该作者
全局:
第一题
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAX 500009
#define N 500000

struct element {
        int value;
        struct element * next;
};

int main(void)
{
        struct element * num[MAX] = {NULL};
        FILE * fin = fopen("HashInt.txt", "r");
        int i, j, index, n_sum;
        int sum[4500] = {0};
        struct element * insert, * temp, * find;
        bool flag;
        for (i = 0; i < N; i++)
        {
                insert = (struct element *) malloc(sizeof(struct element));
                fscanf(fin, "%d", &insert->value);
                insert->next = NULL;
                index = insert->value % MAX;
                if (num[index] == NULL)
                        num[index] = insert;
                else
                {
                        temp = num[index];
                        num[index] = insert;
                        insert->next = temp;
                }
        }
        n_sum = 0;
        for (i = 0; i < MAX; i++)
                if (num[i] != NULL)
                {
                        temp = num[i];
                        while (temp)
                        {
                                for (j = 2500; j <= 4000; j++)
                                        if ((j - (temp->value) > 0) &&
                                                        (num[(j - (temp->value)) % MAX] != NULL)
                                                        && (j - temp->value != temp->value))
                                        {
                                                find = num[(j-(temp->value)) % MAX];
                                                flag = false;
                                                while (find)
                                                {
                                                        if (find->value == j-(temp->value))
                                                                flag = true;
                                                        find = find->next;
                                                }
                                                if (flag)
                                                        sum[j] = 1;
                                        }
                                temp = temp->next;
                        }

                }
        for (i = 0; i < 4001; i++)
                if (sum[i] > 0)
                        n_sum++;
        printf("%d\n", n_sum);
}


第二题
#include <stdio.h>
#define MAX 10000

int find_median(int p[], int n, int insert);

int main(void)
{
        FILE * fin = fopen("Median.txt", "r");
        int num[MAX] = {0};
        int process[MAX] = {0};
        int i, median_sum;
        for (i = 0; i < MAX; i++)
                fscanf(fin, "%d", &num[i]);
        fclose(fin);
        median_sum = 0;
        for (i = 0; i < MAX; i++)
                median_sum += find_median(process, i, num[i]);
        printf("%d\n", median_sum % MAX);
        return 0;
}

int find_median(int p[], int n, int insert)
{
        int i, j;
        i = 0;
        j = 0;
        while ((i < n) && (p[i] < insert))
                i++;
        for (j = n; j > i; j--)
                p[j] = p[j-1];
        p[i] = insert;
        return p[n/2];
}
回复

使用道具 举报

🔗
touchzou 2012-7-28 15:00:38 | 只看该作者
全局:
Problem 1:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>

  4. #define MAX 50000

  5. int tabsize = MAX;


  6. struct node
  7. {
  8.     int label;
  9.     struct node * next;
  10. };

  11. struct node tab[MAX], count[MAX], test[MAX];


  12. void init();

  13. int hash(int);

  14. void insert(int, struct node *);

  15. int lookup(int, struct node *);

  16. void del(int, struct node *);

  17. int size(struct node *);

  18. void read_data(char *);

  19. int main(void)
  20. {
  21.     init();
  22.     read_data("D:\\HashInt.txt");


  23.     insert(1, test);
  24.     size(test);
  25.     insert(1, test);
  26.     size(test);
  27.     insert(1, test);
  28.     size(test);
  29.     size_t begin = time(NULL);
  30.     int x;
  31.     for(x = 0; x < MAX; x++)
  32.     {
  33.         struct node *temp = tab + x;
  34.         if(temp->label == 0)
  35.             continue;
  36.         else
  37.         {
  38.             while(temp != NULL)
  39.             {
  40.                 //printf("%d ->", temp->label);
  41.                 int y;
  42.                 for(y = 2500; y <= 4000; y++)
  43.                 {
  44.                     if(y - temp->label != temp->label && y - temp->label > 0)
  45.                     {
  46.                         if(lookup(y - temp->label, tab))
  47.                         {
  48.                             insert(y, count);
  49.                         }
  50.                     }
  51.                 }
  52.                 temp = temp->next;
  53.             }
  54.         }
  55.     }
  56.     printf("Time spends : %ld\n", time(NULL) - begin);
  57.     printf("The distinct Value is: %d\n", size(count));

  58.     return 0;
  59. }

  60. void init()
  61. {
  62.     int x;
  63.     for(x = 0; x < MAX; x++)
  64.     {
  65.         tab[x].label = 0;
  66.         tab[x].next = NULL;

  67.         count[x].label = 0;
  68.         count[x].next = NULL;

  69.         test[x].label = 0;
  70.         test[x].next = NULL;
  71.     }
  72. }

  73. int hash(int label)
  74. {
  75.     return label % tabsize;
  76. }

  77. void insert(int label, struct node *data)
  78. {
  79.     int index = hash(label);
  80.     struct node * temp = data + index;
  81.     if(temp->label != 0)
  82.     {
  83.         // Collision happened.
  84.         /*
  85.             |Index|Label|Link|    Overflow area
  86.             |   0 |   1 |  ->->   |3|->-> |5|->-> |7|x
  87.             |   1 |   2 |  ->->   |4|->-> |6|x
  88.           */
  89.         if(temp->label == label)
  90.             return;
  91.         while(temp->next != NULL)
  92.         {
  93.             // already in tab, do nothing.
  94.             if(temp->next->label == label)
  95.                 return;
  96.             temp = temp->next;
  97.         }
  98.         // Add a new node to the end of collision list.
  99.         struct node * new_node = malloc(sizeof(struct node));
  100.         new_node->label = label;
  101.         new_node->next = NULL;

  102.         temp->next = new_node;
  103.     }
  104.     else
  105.     {
  106.         temp->label = label;
  107.     }

  108. }

  109. int lookup(int label, struct node * data)
  110. {
  111.    int sign = 0;
  112.    struct node * temp = data + hash(label);
  113.    while(temp != NULL)
  114.    {
  115.        if(temp->label == label)
  116.        {
  117.            sign = 1;
  118.            return sign;
  119.        }
  120.        temp = temp->next;
  121.    }
  122.    return sign;
  123. }

  124. void del(int label, struct node * data)
  125. {
  126.     struct node * temp = data + hash(label);
  127.     if(temp->label == label)
  128.     {
  129.         temp->label = 0;
  130.         return;
  131.     }
  132.     else
  133.     {
  134.         while(temp->next != NULL)
  135.         {
  136.             if(temp->next->label == label)
  137.             {
  138.                 if(temp->next->next == NULL)
  139.                 {
  140.                     free(temp->next);
  141.                     temp->next = NULL;
  142.                     return;
  143.                 }
  144.                 else
  145.                 {
  146.                     struct node * temp_next_next = temp->next->next;
  147.                     free(temp->next);
  148.                     temp->next = temp_next_next;
  149.                     return;
  150.                 }
  151.             }
  152.             temp = temp->next;
  153.         }
  154.     }
  155. }

  156. int size(struct node * data)
  157. {
  158.     int x;
  159.     int c = 0;
  160.     for(x = 0; x < MAX; x++)
  161.     {
  162.         struct node * temp = data + x;
  163.         if(temp->label == 0)
  164.             continue;
  165.         else
  166.         {
  167.             while(temp != NULL)
  168.             {
  169.                 c++;
  170.                 //printf("%d ->", temp->label);
  171.                 temp = temp->next;
  172.             }
  173.         }
  174.         //printf("\n");
  175.     }
  176.     return c;
  177. }

  178. void read_data(char * file)
  179. {
  180.     FILE *fp = fopen(file, "rb");
  181.     int label;
  182.     while(!feof(fp))
  183.     {

  184.         fscanf(fp, "%d ", &label);
  185.         insert(label, tab);
  186.     }
  187. }
复制代码
Problem 2: 开始时结果老是不对,又找不出错误,后来发现Extrate-MAX和Extrate-MIN里面有问题,应该先求Smallest Child(或 Biggest Child)的位置,然后Bubble-Down交换数据.
  1. #include <stdio.h>
  2. #include <time.h>

  3. #define MAX 10000

  4. struct heap
  5. {
  6.     int size;
  7.     int data[MAX];
  8. };

  9. struct heap min_heap, max_heap;

  10. long long count = 0;

  11. void init();

  12. void minheap_insert(int, struct heap *);

  13. int extract_min(struct heap *);

  14. void maxheap_insert(int, struct heap *);
  15. int extract_max(struct heap *);

  16. void swap(int *, int *);

  17. int parent(int);

  18. int smallest_child(int, struct heap *);

  19. int biggest_child(int, struct heap *);

  20. void display(struct heap *);

  21. void read_data(char *);

  22. int main(void)
  23. {
  24.     init();
  25.     read_data("D:\\Median.txt");
  26.     printf("The count mod 10000 is : %d\n", count % 10000);
  27.     return 0;
  28. }

  29. void init()
  30. {
  31.     min_heap.size = 0;
  32.     max_heap.size = 0;
  33.     int x = 0;
  34.     for(x = 0; x < MAX; x++)
  35.     {
  36.         *(min_heap.data + x) = 0;
  37.         *(max_heap.data + x) = 0;
  38.     }
  39. }


  40. void minheap_insert(int label, struct heap * temp)
  41. {
  42.     temp->size += 1;
  43.     int i = temp->size;
  44.     *(temp->data + i - 1) = label;

  45.     int *parent_i_th, *i_th;
  46.     i_th = temp->data + i - 1;
  47.     parent_i_th = temp->data + parent(i) - 1;
  48.     while(*parent_i_th > *i_th)
  49.     {
  50.         swap(parent_i_th, i_th);
  51.         i = parent(i);
  52.         i_th = temp->data + i - 1;
  53.         parent_i_th = temp->data + parent(i) - 1;
  54.     }
  55. }

  56. void maxheap_insert(int label, struct heap * temp)
  57. {

  58.     temp->size += 1;
  59.     int i = temp->size;
  60.     *(temp->data + i - 1) = label;
  61.     int *parent_i_th, *i_th;
  62.     i_th = temp->data + i - 1;
  63.     parent_i_th = temp->data + parent(i) - 1;

  64.     while(*parent_i_th < *i_th)
  65.     {
  66.         swap(parent_i_th, i_th);
  67.         i = parent(i);
  68.         i_th = temp->data + i - 1;
  69.         parent_i_th = temp->data + parent(i) - 1;
  70.     }
  71.     if(label == 1260)
  72.     {
  73.         printf("1260   Test: ");
  74.         display(temp);
  75.     }
  76. }

  77. int extract_min(struct heap * temp)
  78. {
  79.     if(temp->size == 0)
  80.     {
  81.         printf("No more element!\n");
  82.         return -1;
  83.     }
  84.     int result = *(temp->data);
  85.     *(temp->data) = *(temp->data + temp->size - 1);
  86.     temp->size -= 1;
  87.     int i = 1;
  88.     int *i_th, *s_child;
  89.     i_th = temp->data + i - 1;
  90.     s_child = temp->data + smallest_child(i, temp) - 1;
  91.     while(*i_th > *s_child)
  92.     {
  93.         // Attention, Need caculate smallest_child before swap.
  94.         i = smallest_child(i, temp);
  95.         swap(i_th, s_child);
  96.         i_th = temp->data + i - 1;
  97.         s_child = temp->data + smallest_child(i, temp) - 1;
  98.     }
  99.     return result;
  100. }

  101. int extract_max(struct heap * temp)
  102. {
  103.     if(temp->size == 0)
  104.     {
  105.         printf("No more element!\n");
  106.         return -1;
  107.     }
  108.     int result = *(temp->data);
  109.     *(temp->data) = *(temp->data + temp->size - 1);
  110.     temp->size -= 1;
  111.     int i = 1;
  112.     int *i_th, *b_child;
  113.     i_th = temp->data + i - 1;
  114.     b_child = temp->data + biggest_child(i, temp) - 1;
  115.     while(*i_th < *b_child)
  116.     {
  117.         // Attention, Need to caculate biggest_child before swap.
  118.         i = biggest_child(i, temp);
  119.         swap(i_th, b_child);
  120.         i_th = temp->data + i - 1;
  121.         b_child = temp->data + biggest_child(i, temp) - 1;

  122.     }

  123.     return result;
  124. }

  125. void swap(int * label1, int * label2)
  126. {
  127.     int temp = *label2;
  128.     *label2 = *label1;
  129.     *label1 = temp;
  130. }

  131. int parent(int label)
  132. {
  133.     if(label == 1)
  134.         return 1;
  135.     else
  136.         return label/2;
  137. }

  138. int smallest_child(int label, struct heap * temp)
  139. {
  140.     int left_child = label * 2;
  141.     int right_child = label * 2 + 1;
  142.     if(left_child > temp->size)
  143.         return label;
  144.     else if(left_child == temp->size)
  145.         return left_child;
  146.     else
  147.     {
  148.         if(*(temp->data + left_child - 1) <= *(temp->data + right_child - 1))
  149.             return left_child;
  150.         else
  151.             return right_child;
  152.     }
  153. }

  154. int biggest_child(int label, struct heap * temp)
  155. {
  156.     int left_child = label * 2;
  157.     int right_child = label * 2 + 1;
  158.     if(left_child > temp->size)
  159.         return label;
  160.     else if(left_child == temp->size)
  161.         return left_child;
  162.     else
  163.     {
  164.         if(*(temp->data + left_child - 1) > *(temp->data + right_child - 1))
  165.             return left_child;
  166.         else
  167.             return right_child;
  168.     }
  169. }

  170. void display(struct heap * temp)
  171. {
  172.     int x = 0;
  173.     for(x = 0; x < temp->size; x++)
  174.         printf("%d-> ", *(temp->data + x));
  175.     printf("\n");
  176. }

  177. void read_data(char * file)
  178. {
  179.     FILE *fp = fopen(file, "rb");
  180.     int label;
  181.     FILE *wp = fopen("D:\\test.csv", "wb");
  182.     int i = 0;
  183.     while(!feof(fp))
  184.     {
  185.         // Please don't forget the space after %d.
  186.         fscanf(fp, "%d ", &label);
  187.         //printf("Label : %d \n", label);

  188.         if(max_heap.size == 0)
  189.             maxheap_insert(label, &max_heap);
  190.         else
  191.         {
  192.             if(label <= *(max_heap.data))
  193.                 maxheap_insert(label, &max_heap);
  194.             else
  195.                 minheap_insert(label, &min_heap);

  196.             /*
  197.             printf("1Low:%d\n", max_heap.size);
  198.             display(&max_heap);
  199.             printf("1High:%d\n", min_heap.size);
  200.             display(&min_heap);
  201.             */

  202.             if(max_heap.size - min_heap.size > 1)
  203.             {
  204.                 label = extract_max(&max_heap);
  205.                 minheap_insert(label, &min_heap);
  206.             }
  207.             if(max_heap.size < min_heap.size)
  208.             {
  209.                 label = extract_min(&min_heap);
  210.                 maxheap_insert(label, &max_heap);
  211.             }
  212.         }
  213.         /*
  214.         printf("Low:%d\n", max_heap.size);
  215.         display(&max_heap);
  216.         printf("High:%d\n", min_heap.size);
  217.         display(&min_heap);
  218.         */
  219.         int temp;
  220.         temp = *(max_heap.data);
  221.         count += temp;
  222.         fprintf(wp, "%d\n", temp);
  223.         printf("%d th Median: %d \n", ++i, temp);

  224.     }
  225.     fclose(wp);
  226.     fclose(fp);
  227. }
复制代码
回复

使用道具 举报

🔗
EDream 2012-7-28 20:39:48 | 只看该作者
全局:
本帖最后由 EDream 于 2012-7-28 20:42 编辑

看着大家自己写的data strucutre,顿时觉得调用库神马的弱爆了...上代码:
1. Two-Sum Problem
#include <iostream>
#include <vector>
using namespace std;

#define MAX_NUM 4001

const int LB = 2500;
const int HB = 4000;

int hashtable[MAX_NUM];
int target[HB-LB+1];
bool count[HB-LB+1];

int main()
{
        int in_num;
        int i = 1, counter = 0;
        for (int k = 0; k <= (HB-LB); k++) {
                target[k] = 2500 + k;
        }

        FILE* fin = fopen("HashInt.txt", "r");
        while (fscanf(fin, "%d", &in_num) > 0) {
                for (int i = 0; i < (HB-LB+1); i++) {
                        if (target > in_num && hashtable[target[i]-in_num]) {                                                                [/i]
[i]
                                        count[i] = true;                                       

                        }
                }
                if (in_num <= MAX_NUM) {
                        hashtable[in_num]++;
                }
        }

        for (int i = 0; i <= (HB-LB); i++) {
                if (count[i] == true)

                        counter++;
        }

        cout << counter << endl;
        return 0;
}


2. Median Maintenance
#include <iostream>
#include <vector>
#include <queue>
#include <ctime>
using namespace std;

#define N 10000

vector<int> nums;
int median[N];

int getMedian(vector<int> &v)
{
        priority_queue<int> max_heap;
        priority_queue<int, std::vector<int>, std::greater<int>> min_heap;

        //Add element into both heaps
        for (int index = 0; index < v.size(); index++) {
                if (!max_heap.empty() && v[index] < max_heap.top())
                        max_heap.push(v[index]);
                else
                        min_heap.push(v[index]);
[/i][/i][i][i][i]
        //balance both heaps
                if (std::abs((max_heap.size()-min_heap.size())*1.0) > 1.0) {
                        if (max_heap.size() > min_heap.size()) {                        
                                min_heap.push(max_heap.top());
                                max_heap.pop();
                        } else {
                                max_heap.push(min_heap.top());
                                min_heap.pop();
                        }
                }
        }

        if (v.size() % 2 == 0)
                return max_heap.top();
        else
                return max_heap.size() > min_heap.size() ? max_heap.top() : min_heap.top();
}

int main()
{
        FILE* fin = fopen("Median.txt", "r");
        int in_num;
        int i = 0;
        while (fscanf(fin, "%d", &in_num) > 0) {
                nums.push_back(in_num);
                median[i++] = getMedian(nums);
        }
        int sumMedian = 0;
        for (int j = 0; j < N; j++) {
                sumMedian += median[j];
        }
        cout << sumMedian % N << endl;      

        return 0;
}


[/i][/i]
[/i][/i]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表