vendredi 31 mars 2017

Solution with map gave AC and Solution with unordered_map gave WA. why?

I am looking for any difference between map and unordere_map which is now known by most of people.

The problem : Problem Link

the solution with map: Accepted Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    map<int,int> mp;
    map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }    
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;   
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl; 
    return 0;
}

the solution with unordered_map: WA Solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    unordered_map<int,int> mp;
    unordered_map<int,int> ::iterator it;
    int ans = 0;
    for(int i=0;i<N;i++){
        int X;
        cin >> X;
        mp[X]++;
    }     
    for(it=mp.begin();it!=mp.end();++it){
        int X = it->first;   
        //cout<<it->first<<" "<<it->second<<endl;
        ans = max(ans,mp[(X-1)]+mp[(X)]);
    }
    cout<<ans<<endl; 
    return 0;
}

As far as I know that only difference with map and unordered_map is that map contain key in sorted fashion while unordered_map not.

Aucun commentaire:

Enregistrer un commentaire