解いた問題のソースコードと解説など。


POJ 1583 Choose Your Words Carefully

問題

http://poj.org/problem?id=1583
文章が与えられる。最も出現頻度が高い単語を列挙し、かつ頻度を求めよ。

やりかた

連想配列に放り込んでいき、最頻度のstringを保存していけばいい。

int main(){
  string s, t;
  while(cin >> t) s += (t + " ");

  string a;
  map<string, int> occ;
  for(int i = 0; i < (int)s.length(); i++){
    if(isalpha(s[i])) a += tolower(s[i]);//小文字化を忘れない
    else{
      if(!a.empty()) occ[a]++;
      a = "";
    }
  }

  vector<string> freq;
  int cnt = 0;
  for(map<string, int>::iterator it = occ.begin(); it != occ.end();
      it++){
    if(it -> second > cnt){
      cnt = it -> second;
      freq.clear();
      freq.push_back(it -> first);
    }else if(it -> second == cnt)
      freq.push_back(it -> first);
  }

  cout << cnt << " occurrences" << endl;
  for(int i = 0; i < (int)freq.size(); i++)
    cout << freq[i] << endl;
  return 0;
}

なんかつかれた。

Get up! 明日のSUPER ST@R!