Given a line of text you will have to find out the frequencies of the ASCII characters present in it. The given lines will contain none of the first 32 or last 128 ASCII characters. Of course lines may end with ‘\n’ and ‘\r’ but always keep those out of consideration.
Input
Several lines of text are given as input. Each line of text is considered as a single input. Maximum length of each line is 1000.
Output
Print the ASCII value of the ASCII characters which are present and their frequency according to the given format below. A blank line should separate each set of output. Print the ASCII characters in the ascending order of their frequencies. If two characters are present the same time print the information of the ASCII character with higher ASCII value first. Input is terminated by end of file.
Sample Input:
AAABBC122333
Sample Output:
67 166 2
65 3
49 1
50 2
51 3
出處: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1003
這題我不是採用暴力法(雖然程式碼比較簡潔),我是採用排序的方式,作法和 http://samchien.blogspot.tw/2013/04/10008-whats-cryptanalysis.html 十分類似,所以以下就不贅述。
比較需要注意的地方是input資料的ascii code範圍會包含空白,所以會需要用到能讀取一整行input的方式。
以下是c++程式碼:
#include <iostream> #include <map> #include <vector> #include <algorithm> using namespace std; class Freq { public: int ascii, times; }; bool freqCmp(const Freq* theFreq, const Freq* otherFreq) { if (theFreq->times < otherFreq->times) return true; else if (theFreq->times == otherFreq->times) return theFreq->ascii > otherFreq->ascii; else return false; } int main() { string input; bool firstTime = true; while (getline(cin, input)) { map<int, int> table; vector<int> keyList; vector<Freq*> freqList; for (int i=0; i<input.length(); i++) { if (!table[input[i]]) keyList.push_back(input[i]); table[input[i]]++; } for (int i=0; i<keyList.size(); i++) { Freq* f = new Freq(); f->ascii = keyList[i]; f->times = table[keyList[i]]; freqList.push_back(f); } sort(freqList.begin(), freqList.end(), freqCmp); if (firstTime) firstTime = false; else cout << endl; for (int i=0; i<freqList.size(); i++) cout << freqList[i]->ascii << " " << freqList[i]->times << endl; for (int i=0; i<freqList.size(); i++) delete freqList[i]; } return 0; }
沒有留言:
張貼留言