我對一個小程式的兩次重構過程

來源:互聯網
上載者:User

源於CSDN上一位網友提出的一個問題:

 

演算法實驗題1.2 等式數量
★問題描述
集合是基本的數學概念,集合中的元素是互不相同的。
表示相等關係的式子叫做等式。
給你一個包含有N個整數的集合,如果從集合中找到三個不同的整數a,b,c, 使得
a+b=c,那麼我們說這個集合包含一個等式。
★編程任務
計算集合中所包含的等式數量。
★資料輸入
第一行為一個整數N (3 <=N <=5,000),表示集合中有N個不同的整數。第二行有N個整
數,表示集合中的元素,元素的整數值大小為-10000000~10000000。
★資料輸出
輸出一行一個整數,表示該集合的等式數量。
輸入檔案樣本輸出檔案樣本
input.txt output.txt
4        2
3125
http://topic.csdn.net/u/20090828/10/f41bc15e-339c-4b55-b1a6-2f4b3383a107.html?seed=547430668&r=59420060#r_59420060

 

他的演算法是用三重迴圈來做。演算法複雜度為n*n*n。

 

我能想到的就是改進為n*n*log(n)了,將其中的一層改進為二叉樹結構。

 

初始程式:

我首先想到的是利用STL的map,它是基於樹的。

#include <iostream><br />#include <sstream><br />#include <fstream><br />#include <cstdlib><br />#include <bitset><br />#include <vector><br />#include <map><br />#include <algorithm></p><p>namespace {<br /> const int LOW_VAL_BOUND = -10000000;<br /> const int HIGH_VAL_BOUND = 10000000;<br /> const size_t LOW_SIZE_BOUND = 3;<br /> const size_t HIGH_SIZE_BOUND = 5000;</p><p> typedef std::vector<std::pair<int, int> > Vecpii;<br /> typedef std::map<int, Vecpii> Mapipii;<br />}</p><p>bool ReadInputFile(std::ifstream& in, Mapipii& judge, std::vector<int>& num)<br />{<br /> using namespace std;<br /> size_t count;</p><p> in >> count;<br /> if (!(LOW_SIZE_BOUND<=count && count<=HIGH_SIZE_BOUND)) return false;</p><p> while(in.good()) {<br /> int n;<br /> in >> n;<br /> if (!(LOW_VAL_BOUND<=n && n<=HIGH_VAL_BOUND)) return false;</p><p> for(vector<int>::iterator iter=num.begin(); iter != num.end(); ++iter) {<br /> Vecpii& addForm = judge[n+*iter];<br /> addForm.push_back(pair<int, int>(n,*iter));<br /> }<br /> num.push_back(n);<br /> }<br /> if(num.size()!=count) return false;<br /> return true;<br />}</p><p>std::ostream& operator<<(std::ostream& out, const Vecpii& aVector)<br />{<br /> for(Vecpii::const_iterator cit=aVector.begin(); cit != aVector.end(); ++cit) {<br /> const std::pair<int, int>& aPair = *cit;<br /> out << aPair.first << '+'<br /> << aPair.second << '='<br /> << aPair.first+aPair.second << std::endl;<br /> }<br /> return out;<br />}</p><p>int main ( )<br />{<br /> using namespace std;<br /> Mapipii judge;<br /> vector<int> num;</p><p> ifstream in("input.txt");<br /> if(!in.good() || !ReadInputFile(in, judge, num)) {<br /> cout << "error!/n";<br /> in.close();<br /> exit(1);<br /> }<br /> in.close();</p><p> int total=0;<br /> for(vector<int>::const_iterator cit=num.begin(); cit != num.end(); ++cit) {<br /> int n = *cit;<br /> if(judge.find(n) != judge.end()) {<br /> cout << judge[n];<br /> ++total;<br /> }<br /> }</p><p> ofstream out("output.txt");<br /> out << total;<br /> cout << "/nTotal := " << total;<br /> out.close();</p><p> cout << endl;<br /> system("pause");<br /> return 0;<br />}</p><p>

隨後我用5000個資料做了壓力測試,速度實在是慢42.001秒,記憶體佔用729MB,受不了。。。

 

第一次重構:

鑒於LZ不要列印過程,我把map改成了set,則不需要添加map的vector了。

#include <iostream><br />#include <fstream><br />#include <vector><br />//#include <map><br />#include <set><br />#include <ctime><br />//#include <algorithm></p><p>namespace {<br /> const int LOW_VAL_BOUND = -10000000;<br /> const int HIGH_VAL_BOUND = 10000000;<br /> const size_t LOW_SIZE_BOUND = 3;<br /> const size_t HIGH_SIZE_BOUND = 5000;<br />}</p><p>bool ReadInputFile(std::ifstream& in, std::set<int>& judge, std::vector<int>& num)<br />{<br /> using namespace std;<br /> size_t count;</p><p> in >> count;<br /> if (!(LOW_SIZE_BOUND<=count && count<=HIGH_SIZE_BOUND)) return false;</p><p> num.assign(count, 0);<br /> size_t i=0;<br /> while(in.good()) {<br /> int n;<br /> in >> n;<br /> if (!(LOW_VAL_BOUND<=n && n<=HIGH_VAL_BOUND)) return false;<br /> num[i++]=n;<br /> }<br /> if(i!=count) return false;</p><p> for(vector<int>::iterator ita=num.begin(); ita != num.end(); ++ita) {<br /> for(vector<int>::iterator itb=num.begin(); itb != num.end(); ++itb) {<br /> if(ita != itb) judge.insert(*ita + *itb);<br /> }<br /> }</p><p> return true;<br />}</p><p>int main ( )<br />{<br /> clock_t start = clock();<br /> using namespace std;<br /> set<int> judge;<br /> vector<int> num;</p><p> ifstream in("input.txt");<br /> if(!in.good() || !ReadInputFile(in, judge, num)) {<br /> cout << "error!/n";<br /> in.close();<br /> exit(1);<br /> }<br /> in.close();</p><p> int total=0;<br /> for(vector<int>::const_iterator cit=num.begin(); cit != num.end(); ++cit) {<br /> if(judge.find(*cit) != judge.end()) ++total;<br /> }</p><p> ofstream out("output.txt");<br /> out << total;<br /> cout << "Total := " << total;</p><p> cout << endl;<br /> cout << "Time using: "<< (double)(clock()-start)/CLOCKS_PER_SEC << endl;</p><p> system("pause");<br /> return 0;<br />}

重構之後,記憶體佔用降到322M,時間為30.01秒。演算法複雜度不變。
當時我還說:不過對於LZ的要求應該是達到了,一般的資料量也能接受。


第二次重構:

晚上回去想想,這占記憶體也太大了,我想到用vector <bool>,這是vector的一個特化版本,主要是空間上的節約(大概省了30左右吧),另外不用動態new,時間也省了不少,而且尋找是常數時間,而不是對數時間。

 #include <iostream><br />#include <fstream><br />#include <vector><br />#include <bitset><br />#include <ctime><br />#include <algorithm></p><p>namespace {<br /> const int LOW_VAL_BOUND = -10000000;<br /> const int HIGH_VAL_BOUND = 10000000;<br /> const size_t LOW_SIZE_BOUND = 3;<br /> const size_t HIGH_SIZE_BOUND = 5000;<br /> const size_t OFFSET = HIGH_VAL_BOUND-LOW_VAL_BOUND;<br />}</p><p>bool ReadInputFile(std::ifstream& in, std::vector<bool>& judge, std::vector<int>& num)<br />{<br /> using namespace std;<br /> size_t count;</p><p> in >> count;<br /> if (!(LOW_SIZE_BOUND<=count && count<=HIGH_SIZE_BOUND)) return false;</p><p> num.assign(count, 0);<br /> size_t i=0;<br /> while(in.good()) {<br /> int n;<br /> in >> n;<br /> if (!(LOW_VAL_BOUND<=n && n<=HIGH_VAL_BOUND)) return false;<br /> num[i++]=n;<br /> }<br /> if(i!=count) return false;</p><p> sort(num.begin(), num.end());<br /> judge.assign(*(num.end()-1)+OFFSET, false);</p><p> size_t tmp;<br /> for(size_t i=0; i < num.size(); ++i) {<br /> for(size_t j=i+1; j<num.size(); ++j) {<br /> tmp = num[i] + num[j] + OFFSET;<br /> if(tmp <= judge.size()) judge[tmp-1]=true;<br /> }<br /> }</p><p> return true;<br />}</p><p>int main ( )<br />{<br /> clock_t start = clock();<br /> using namespace std;<br /> vector<bool> judge;<br /> vector<int> num;</p><p> ifstream in("input.txt");<br /> if(!in.good() || !ReadInputFile(in, judge, num)) {<br /> cout << "error!/n";<br /> in.close();<br /> exit(1);<br /> }<br /> in.close();</p><p> int total=0;<br /> for(vector<int>::const_iterator cit=num.begin(); cit != num.end(); ++cit) {<br /> if(judge[*cit-1+OFFSET]) ++total;<br /> }</p><p> ofstream out("output.txt");<br /> out << total;<br /> cout << "Total := " << total;<br /> out.close();</p><p> cout << endl;<br /> cout << "Time using: "<< (double)(clock()-start)/CLOCKS_PER_SEC << endl;</p><p> system("pause");<br /> return 0;<br />}<br />

我還是用昨晚的5000個資料做壓力測試,記憶體佔用降到4M,時間為1.306秒(Release,P4 3.0G,1G記憶體)。我已經很滿意了。演算法複雜度不變。

 

我從這次重構中學到兩點:

1. 演算法複雜度不變,不代表沒有最佳化的空間了,正如上面如得,第三個程式比第一個空間上最佳化150多倍,時間上最佳化40多倍。

2.STL的容器空間分配子只能針對大部分情況是好的,對於某些情況還是得用自己的分配子,例如,如果我一定用map,那麼我可以自己做一個分配子,使得記憶體集中存放,這樣就不用那麼多的new操作。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.