たなしょのメモ

日々勉強していることをつらつらと

C - Poll

はじめに

たなしょです。

うーん。ほろ苦い敗戦です。

ここ最近C問題もクリアしてきただけに悔しいです。

問題文

atcoder.jp

考え方

連想配列を作成して連想配列に文字列を入れていきます。

map<string, int> m;

    int n;
    cin >> n;

    for (int i = 0; i < n; i++) {
        string s;
        cin >> s;

        m[s] += 1;
    }

連想配列の2番目(対象文字列の個数)を比較していき最大値を取得する。

 int max = 0;
    for (const auto& x : m) {
        int a = x.second;
        if (a > max)
            max = a;
    }

連想配列を頭から回していき最大値の個数をとる文字列を出力する。

 for (auto i = m.begin(); i != m.end(); i++) {
        if (i->second == max)
            cout << i->first << endl;
    }

いざ実装

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <map>
typedef long long ll;

using namespace std;

int main(void)
{
    map<string, int> m;

    int n;
    cin >> n;

    for (int i = 0; i < n; i++) {
        string s;
        cin >> s;

        m[s] += 1;
    }

    int max = 0;
    for (const auto& x : m) {
        int a = x.second;
        if (a > max)
            max = a;
    }

    for (auto i = m.begin(); i != m.end(); i++) {
        if (i->second == max)
            cout << i->first << endl;
    }

    return 0;
}

あれ?

ローカルでのコンパイルも通ったことだし、いざAtCoder環境で実行!

./Main.cpp: In function ‘int main()’:
./Main.cpp:28:22: error: ISO C++ forbids declaration of ‘x’ with no type [-fpermissive]
     for (const auto& x : m) {
                      ^
./Main.cpp:28:26: warning: range-based ‘for’ loops only available with -std=c++11 or -std=gnu++11
     for (const auto& x : m) {
                          ^
./Main.cpp:29:19: error: request for member ‘second’ in ‘x’, which is of non-class type ‘const intint a = x.second;
                   ^
./Main.cpp:34:15: error: ‘i’ does not name a type
     for (auto i = m.begin(); i != m.end(); i++) {
               ^
./Main.cpp:34:30: error: expected ‘;’ before ‘i’
     for (auto i = m.begin(); i != m.end(); i++) {
                              ^
./Main.cpp:34:30: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
./Main.cpp:34:30: note: (if you use ‘-fpermissive’ G++ will accept your code)
./Main.cpp:34:32: error: no match foroperator!=’ (operand types are ‘intand ‘std::map<std::basic_string<char>, i...

あれれ?コンパイルエラーどうして?

ISO C++は型のない宣言は禁止している?

auto& xがいけないのか。

といろいろ直してみても結局動かず謎が残るコードになってしまいました。

最後に

なにがいけないんだろう。悔しい。

後一歩のところで完全に集中力が切れてしまい中止。

3週連続のc問題完了はできませんでした。

最後まで読んでいただいてありがとうございました。 もしよろしければtwitterアカウント(@piklus100yen)もフォローしていただけると幸いです!