2亿个整数中求最大的100万之和

2亿个整数中求最大的100万之和

题目:有一个文件中保存了2亿个整数,每个整数都以' '分隔。求最大的100万个整数之和。

算法:
1. 首先建立一个容量为100万(nTop)的int数组,从文件读取整数填充。
2. 利用堆维护该100万条记录(确保堆顶元素为最小值)
3. 从文件中读取一个整数与堆顶元素比较,如果大于堆顶元素则替换该元素,并调整堆的结构。
4. 重复步骤3一直到数据读取完
5. 将数组中的元素全部相加,得到结果

参考源代码:

[cpp]  view plain copy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. template<class T>  
  5. class CTopK  
  6. {  
  7. public:  
  8.     CTopK();  
  9.     ~CTopK();  
  10.     T*  m_Data;  
  11.     int GetTopK(const char* sFile, int& nTop);  
  12. private:  
  13.     void Clear();  
  14.     void HeapAdjust(int nStart, int nLen);  
  15.     void BuildHeap(int nLen);  
  16. };  
  17.   
  18. template<class T>  
  19. CTopK<T>::CTopK()  
  20. {  
  21.     m_Data = NULL;  
  22. }  
  23.   
  24. template<class T>  
  25. CTopK<T>::~CTopK()  
  26. {  
  27.     Clear();  
  28. }  
  29.   
  30. template<class T>  
  31. void CTopK<T>::Clear()  
  32. {  
  33.     if (NULL != m_Data)  
  34.     {  
  35.         delete[] m_Data;  
  36.         m_Data = NULL;  
  37.     }  
  38. }  
  39.   
  40. //获取前top的k个数  
  41. template<class T>  
  42. int CTopK<T>::GetTopK(const char* sFile, int& nTop)  
  43. {  
  44.     FILE* fp = NULL;  
  45.     T fData;  
  46.     int i = 0;  
  47.   
  48.     //判断输入参数  
  49.     if ( (NULL == sFile) || (nTop <= 0) )  
  50.     {  
  51.         cout << "error parameter" << endl;  
  52.         return -1;  
  53.     }  
  54.   
  55.     //清除操作  
  56.     Clear();  
  57.   
  58.     //打开文件  
  59.     fp = fopen(sFile, "r");  
  60.     if (NULL == fp)  
  61.     {  
  62.         cout << "open file failed!" << endl;  
  63.         return -1;  
  64.     }  
  65.   
  66.     //分配空间  
  67.     m_Data = new T[nTop];  
  68.     if (NULL == m_Data)  
  69.     {  
  70.         cout << "new operator failed!" << endl;  
  71.         return -1;  
  72.     }  
  73.   
  74.     cout << "please wait..." << endl;  
  75.   
  76.     //读取前nTop个数据,注意数据的类型T  
  77.     for (i = 0; i < nTop; i++)  
  78.     {  
  79.         if (EOF != fscanf(fp, "%d", &fData))  
  80.         {  
  81.             m_Data[i] = fData;  
  82.         }  
  83.         else  
  84.         {  
  85.             break;  
  86.         }  
  87.     }  
  88.   
  89.     //最大的个数小于nTop,求前i个数据  
  90.     if (i < nTop)  
  91.     {  
  92.         nTop = i;  
  93.     }  
  94.     else  
  95.     {  
  96.         BuildHeap(nTop);//建立小顶堆  
  97.   
  98.         while (EOF != fscanf(fp, "%d", &fData))  
  99.         {  
  100.             if (fData > m_Data[0])  
  101.             {  
  102.                 //交换并调整堆  
  103.                 m_Data[0] = fData;  
  104.                 HeapAdjust(0, nTop);  
  105.             }  
  106.         }  
  107.     }  
  108.   
  109.     return 0;  
  110. }  
  111.   
  112. //调整小根堆,堆顶为Top K最小  
  113. template<class T>  
  114. void CTopK<T>::HeapAdjust(int nStart, int nLen)  
  115. {  
  116.     int nMinChild = 0;  
  117.     T fTemp;  
  118.   
  119.     while ( ( 2 * nStart + 1) < nLen)  
  120.     {  
  121.         nMinChild = 2 * nStart + 1;  
  122.         if ( (2 * nStart + 2) < nLen)  
  123.         {  
  124.             //比较左子树和右子树,记录最小值的Index  
  125.             if (m_Data[2 * nStart + 2] < m_Data[2 * nStart + 1])  
  126.             {  
  127.                 nMinChild = 2 * nStart + 2;  
  128.             }  
  129.         }  
  130.   
  131.         //change data  
  132.         if (m_Data[nStart] > m_Data[nMinChild])  
  133.         {  
  134.             //交换nStart与nMaxChild的数据  
  135.             fTemp = m_Data[nStart];  
  136.             m_Data[nStart] = m_Data[nMinChild];  
  137.             m_Data[nMinChild] = fTemp;  
  138.   
  139.             //堆被破坏,需要重新调整  
  140.             nStart = nMinChild;  
  141.         }  
  142.         else  
  143.         {  
  144.             //比较左右孩子均大则堆未破坏,不再需要调整  
  145.             break;  
  146.         }  
  147.     }  
  148. }  
  149.   
  150. //建立堆  
  151. template<class T>  
  152. void CTopK<T>::BuildHeap(int nLen)  
  153. {  
  154.     int i = 0;  
  155.     T nTemp;  
  156.   
  157.     //将m_Data[0, Len-1]建成小根堆,这里只维护一个小根堆,不排序  
  158.     for (i = nLen / 2  - 1; i >= 0; i--)  
  159.     {  
  160.         HeapAdjust(i, nLen);  
  161.     }  
  162. }  
  163.   
  164. int main(int argc, char* argv[])  
  165. {  
  166.     char   szFile[100] = {0};  
  167.     int     nNum = 0;  
  168.     CTopK<int> objTopSum;  
  169.   
  170.     cout << "please input count file name:" << endl;  
  171.     cin >> szFile;  
  172.     cout << "please input top num:"<< endl;  
  173.     cin >> nNum;  
  174.     objTopSum.GetTopK(szFile, nNum);  
  175.   
  176.     int fSum = 0;  
  177.     for (int i = 0; i < nNum; i++)  
  178.     {  
  179.         cout<<objTopSum.m_Data[i]<<" ";  
  180.         fSum += objTopSum.m_Data[i];  
  181.     }  
  182.     cout << "\ntop " << nNum << " value = " << fSum << endl;  
  183.   
  184.     return 0;  
  185. }  

 

搜索引擎热门查询统计

题目描述:
    搜索引擎会通过日志文件把用户每次检索使用的所有检索串都记录下来,每个查询串的长度为1-255字节。
    假设目前有一千万个记录,这些查询串的重复度比较高,虽然总数是1千万,但如果除去重复后,不超过3百万个。一个查询串的重复度越高,说明查询它的用户越多,也就是越热门。请你统计最热门的10个查询串,要求使用的内存不能超过1G。

    解决方法:hash表+堆

    第一步、先对这批海量数据预处理,在O(N)的时间内用Hash表完成统计;
    第二步、借助堆这个数据结构,找出Top K,时间复杂度为NlogK。即借助堆结构,我们可以在log量级的时间内查找和调整/移动。因此,维护一个K(该题目中是10)大小的小根堆(Kmin设为堆顶元素),然后遍历300万的Query,分别和Kmin进行对比比较(若X>Kmin,则更新并调整堆,否则,不更新),我们最终的时间复杂度是:O(N) + N'*O(logK),(N为1000万,N’为300万)。

    为了降低实现上的难度,假设这些记录全部是一些英文单词,即用户在搜索框里敲入一个英文单词,然后查询搜索结果,最后,要你统计输入单词中频率最大的前K个单词。复杂问题简单化了之后,编写代码实现也相对轻松多了,如下:

[cpp]  view plain copy
  1. //copyright@yansha &&July    
  2. //July、updated,2011.05.08    
  3.     
  4. //题目描述:    
  5. //搜索引擎会通过日志文件把用户每次检索使用的所有检索串都记录下来,每个查询串的    
  6. //长度为1-255字节。假设目前有一千万个记录(这些查询串的重复度比较高,虽然总数是1千万,但如果    
  7. //除去重复后,不超过3百万个。一个查询串的重复度越高,说明查询它的用户越多,也就是越热门),    
  8. //请你统计最热门的10个查询串,要求使用的内存不能超过1G。    
  9.     
  10. #include <iostream>    
  11. #include <string>    
  12. #include <assert.h>    
  13. using namespace std;    
  14.     
  15. #define HASHLEN 2807303    
  16. #define WORDLEN 30    
  17.     
  18. // 结点指针    
  19. typedef struct node_no_space *ptr_no_space;    
  20. typedef struct node_has_space *ptr_has_space;    
  21. ptr_no_space head[HASHLEN];    
  22.     
  23. struct node_no_space     
  24. {    
  25.     char *word;    
  26.     int count;    
  27.     ptr_no_space next;    
  28. };    
  29.     
  30. struct node_has_space    
  31. {    
  32.     char word[WORDLEN];    
  33.     int count;    
  34.     ptr_has_space next;    
  35. };    
  36.     
  37. // 最简单hash函数    
  38. int hash_function(const char *p)    
  39. {    
  40.     int value = 0;    
  41.     while (*p != '\0')    
  42.     {    
  43.         value = value * 31 + *p++;    
  44.         if (value > HASHLEN)    
  45.             value = value % HASHLEN;    
  46.     }    
  47.     return value;    
  48. }    
  49.     
  50. // 添加单词到hash表    
  51. void append_word(const char *str)    
  52. {    
  53.     int index = hash_function(str);    
  54.     ptr_no_space p = head[index];    
  55.     while (p != NULL)    
  56.     {    
  57.         if (strcmp(str, p->word) == 0)    
  58.         {    
  59.             (p->count)++;    
  60.             return;    
  61.         }    
  62.         p = p->next;    
  63.     }    
  64.         
  65.     // 新建一个结点    
  66.     ptr_no_space q = new node_no_space;    
  67.     q->count = 1;    
  68.     q->word = new char [strlen(str)+1];    
  69.     strcpy(q->word, str);    
  70.     q->next = head[index];    
  71.     head[index] = q;    
  72. }    
  73.     
  74.     
  75. // 将单词处理结果写入文件    
  76. void write_to_file()    
  77. {    
  78.     FILE *fp = fopen("result.txt""w");    
  79.     assert(fp);    
  80.         
  81.     int i = 0;    
  82.     while (i < HASHLEN)    
  83.     {    
  84.         for (ptr_no_space p = head[i]; p != NULL; p = p->next)    
  85.             fprintf(fp, "%s  %d\n", p->word, p->count);    
  86.         i++;    
  87.     }    
  88.     fclose(fp);    
  89. }    
  90.     
  91. // 从上往下筛选,保持小根堆    
  92. void sift_down(node_has_space heap[], int i, int len)    
  93. {    
  94.     int min_index = -1;    
  95.     int left = 2 * i;    
  96.     int right = 2 * i + 1;    
  97.         
  98.     if (left <= len && heap[left].count < heap[i].count)    
  99.         min_index = left;    
  100.     else    
  101.         min_index = i;    
  102.         
  103.     if (right <= len && heap[right].count < heap[min_index].count)    
  104.         min_index = right;    
  105.         
  106.     if (min_index != i)    
  107.     {    
  108.         // 交换结点元素    
  109.         swap(heap[i].count, heap[min_index].count);    
  110.             
  111.         char buffer[WORDLEN];    
  112.         strcpy(buffer, heap[i].word);    
  113.         strcpy(heap[i].word, heap[min_index].word);    
  114.         strcpy(heap[min_index].word, buffer);    
  115.             
  116.         sift_down(heap, min_index, len);    
  117.     }    
  118. }    
  119.     
  120. // 建立小根堆    
  121. void build_min_heap(node_has_space heap[], int len)    
  122. {    
  123.     if (heap == NULL)    
  124.         return;    
  125.         
  126.     int index = len / 2;    
  127.     for (int i = index; i >= 1; i--)    
  128.         sift_down(heap, i, len);    
  129. }    
  130.     
  131. // 去除字符串前后符号    
  132. void handle_symbol(char *str, int n)    
  133. {    
  134.     while (str[n] < '0' || (str[n] > '9' && str[n] < 'A') || (str[n] > 'Z' && str[n] < 'a') || str[n] > 'z')    
  135.     {    
  136.         str[n] = '\0';    
  137.         n--;    
  138.     }    
  139.         
  140.     while (str[0] < '0' || (str[0] > '9' && str[0] < 'A') || (str[0] > 'Z' && str[0] < 'a') || str[0] > 'z')    
  141.     {    
  142.         int i = 0;    
  143.         while (i < n)    
  144.         {    
  145.             str[i] = str[i+1];    
  146.             i++;    
  147.         }    
  148.         str[i] = '\0';    
  149.         n--;    
  150.     }    
  151. }    
  152.     
  153. int main()    
  154. {    
  155.     char str[WORDLEN];    
  156.     for (int i = 0; i < HASHLEN; i++)    
  157.         head[i] = NULL;    
  158.         
  159.     // 将字符串用hash函数转换成一个整数并统计出现频率    
  160.     FILE *fp_passage = fopen("string.txt""r");    
  161.     assert(fp_passage);    
  162.     while (fscanf(fp_passage, "%s", str) != EOF)    
  163.     {    
  164.         int n = strlen(str) - 1;    
  165.         if (n > 0)    
  166.             handle_symbol(str, n);    
  167.         append_word(str);    
  168.     }    
  169.     fclose(fp_passage);    
  170.         
  171.     // 将统计结果输入文件    
  172.     write_to_file();    
  173.         
  174.     int n = 10;    
  175.     ptr_has_space heap = new node_has_space [n+1];    
  176.         
  177.     int c;    
  178.         
  179.     FILE *fp_word = fopen("result.txt""r");    
  180.     assert(fp_word);    
  181.     for (int j = 1; j <= n; j++)    
  182.     {    
  183.         fscanf(fp_word, "%s %d", &str, &c);    
  184.         heap[j].count = c;    
  185.         strcpy(heap[j].word, str);    
  186.     }    
  187.         
  188.     // 建立小根堆    
  189.     build_min_heap(heap, n);    
  190.         
  191.     // 查找出现频率最大的10个单词    
  192.     while (fscanf(fp_word, "%s %d", &str, &c) != EOF)    
  193.     {    
  194.         if (c > heap[1].count)    
  195.         {    
  196.             heap[1].count = c;    
  197.             strcpy(heap[1].word, str);    
  198.             sift_down(heap, 1, n);    
  199.         }    
  200.     }    
  201.     fclose(fp_word);    
  202.         
  203.     // 输出出现频率最大的单词    
  204.     for (int k = 1; k <= n; k++)    
  205.         cout << heap[k].count << " " << heap[k].word << endl;    
  206.         
  207.     return 0;    
  208. }    

 

参考:

http://blog.csdn.net/andylin02/archive/2008/11/28/3401123.aspx

http://blog.csdn.net/v_JULY_v/archive/2011/05/08/6403777.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值