Skip to content

Instantly share code, notes, and snippets.

@hanji
Created January 6, 2012 06:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanji/1569347 to your computer and use it in GitHub Desktop.
Save hanji/1569347 to your computer and use it in GitHub Desktop.
find out passwords most frequently used by CSDN users
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
int main()
{
typedef std::unordered_map<std::string, std::size_t> Dict;
typedef std::vector<std::pair<std::string, std::size_t> > Heap;
const std::size_t K = 1000;
const std::size_t Col = 3;
const char sep[] = "\t ";
char line[BUFSIZ];
char *token, *context;
Dict dict;
Heap heap;
while (::fgets(line, BUFSIZ, stdin)) {
for (std::size_t i = 0; i < Col; ++i) {
token = ::strtok_s((0 == i) ? line : NULL, sep, &context);
}
dict[token] = dict[token] + 1;
}
heap.resize(dict.size());
std::transform(dict.begin(), dict.end(), heap.begin(), [](const Dict::value_type& elem){ return std::make_pair(elem.first, elem.second); });
std::partial_sort(heap.begin(), heap.begin() + K, heap.end(), [](const Heap::value_type& a, const Heap::value_type& b){ return a.second > b.second; });
std::for_each(heap.begin(), heap.begin() + K, [](const Heap::value_type& elem){ std::cout << elem.first << " " << elem.second << "\n"; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment