2017-03-31 148 views
-2

我在寻找mapunordere_map之间的任何差异,现在大多数人都知道这个差异。地图解决方案给AC和解决方案与unordered_map给WA。为什么?

问题:Problem Link

地图解决方案: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; 
} 

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; 
} 


Input : 
     98 
     7 12 13 19 17 7 3 18 9 18 13 12 3 13 7 9 18 9 18 9 13 18 13 13 18 18 17 17 13 3 12 13 19 17 19 12 18 13 7 3 3 12 7 13 7 3 17 9 13 13 13 12 18 18 9 7 19 17 13 18 19 9 18 18 18 19 17 7 12 3 13 19 12 3 9 17 13 19 12 18 13 18 18 18 17 13 3 18 19 7 12 9 18 3 13 13 9 7 
Output : 10 
Expected Output : 30 

据我所知,只有与mapunordered_map差异该地图是否包含以分类方式存在的关键字,而unordered_map不是。

+0

作为[MCVE]的一部分,您需要提供输入以及问题主体中的预期和观察输出。请编辑它们,链接到外部网站要求我们做更多的工作,并增加链接腐烂的风险,使您的问题对未来的读者无法理解。 – ShadowRanger

+0

我也提供了输入和期望的输出。我把链接放在了更多的说明中。无论如何,问题有足够的信息。 –

回答

2

mp[(X-1)]可能需要在地图中插入新元素(如果密钥X-1已不存在)。使用std::map,插入新元素不会使任何现有的迭代器失效。使用std::unordered_map,它可能(如果插入恰好触发重新哈希)。当它确实时,it变得无效,并且随后的++it表现出未定义的行为。

+0

由于 现在它的工作如 //简单的检查,访问 之前如果(mp.find(X-1)!= mp.end()){ ANS = MAX(ANS,熔点[(X-1) ] +熔点[(X)]); } –