2013年8月11日

UVa 860 - Entropy Text Analyzer

#include <cstdio>
#include <cctype>
#include <cmath>
#include <sstream>
#include <string>
#include <map>
using namespace std;

map<string, int> dic;
int size;

void handle(string & s) {
  for (int i = 0; s[i]; i++) {
    if (s[i] == ',' || s[i] == '.' || s[i] == ':' || s[i] == ';' || s[i] == '!'
      || s[i] == '?' || s[i] == '\"' || s[i] == '(' || s[i] == ')') {
      s[i] = ' ';
    }
  }
  istringstream ss(s);
  string word;
  while (ss >> word) {
    for (int i = 0; word[i]; i++) {
      word[i] = tolower(word[i]);
    }
    dic[word]++;
    size++;
  }
}

int main() {
  char temp[999];
  while (gets(temp)) {
    string s(temp);
    if (s == "****END_OF_INPUT****") {
      return 0;
    }
    dic.clear();
    size = 0;
    while (s != "****END_OF_TEXT****") {
      handle(s);
      gets(temp);
      s = string(temp);
    }
    double eM = log10(size);
    double eT = 0;
    for (map<string, int>::iterator it = dic.begin(); it != dic.end(); it++) {
      eT += (it->second) * (eM - log10(it->second));
    }
    eT /= size;
    printf("%d %.1lf %.0lf\n", size, eT, eT / eM * 100.0);
  }
}

沒有留言:

張貼留言