#UVa:484-The Department of Redundancy Department

灆洢 2015-01-15 01:02:55

使用C++中的map去做Hash,sort()去做排序即可。

C++(0.023)

/*******************************************************/
/* UVa 484 The Department of Redundancy Department     */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2015/01/15                                 */
/*******************************************************/
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

struct Value{
  int count;
  int order;

  Value(int c = 0, int o = 0){
    count = c;
    order = o;
  }
};

bool compareByValue( const pair<int, Value> &a, const pair<int, Value> &b ){
  if( a.second.order <= b.second.order ) return true;
  return false;
}

int main(){
  map<int, Value> uniqueIntegers;
  int key, order = 1;
  while( scanf("%d", &key) != EOF ){
    if( uniqueIntegers.find(key) == uniqueIntegers.end() ){
      uniqueIntegers[key] = Value(1, order++);
    }
    else{
      ++(uniqueIntegers[key].count);
    }
  }

  vector< pair<int, Value> > sortedIntegers(uniqueIntegers.begin(), 
                                            uniqueIntegers.end());
  sort( sortedIntegers.begin(), sortedIntegers.end(), compareByValue );

  for( vector< pair<int, Value> >::iterator it = sortedIntegers.begin() ;
       it != sortedIntegers.end() ; 
       ++it ){
    printf("%d %d\n", it->first, it->second.count );
  }
  return 0;
}

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料