HDU 1263 水果 (map精简版)

HDU 1263 水果

map嵌套。特判了产地为空、产地不为空但水果为空的情况。

#include <bits/stdc++.h>
using namespace std;
int T,n,w;
string place,fruit;
map<string,map<string,int> >vis;
int main()
{
    ios::sync_with_stdio(false);
    cin>>T;
    while(T--)
    {
        cin>>n;
        vis.clear();
        for(int i=1;i<=n;i++)
        {
            cin>>fruit>>place>>w;
            if(!vis.count(place))//产地为空
            {
                map<string,int>tmp;
                tmp.clear();
                tmp.insert(pair<string,int>(fruit,w));
                vis.insert(pair<string,map<string,int> >(place,tmp));
            }
            else//产地不为空
            {
                if(!vis[place][fruit]) vis[place].insert(pair<string,int>(fruit,w));//水果为空
                else vis[place][fruit]+=w;
            }
        }
        for(auto i:vis)
        {
            string pl=i.first;
            printf("%s\n",pl.c_str());
            for(auto j:i.second)
            {
                string fr=j.first;
                int sumw=j.second;
                printf("   |----%s(%d)\n",fr.c_str(),sumw);
            }
        }
        if(T!=0)printf("\n");
    }
    return 0;
}

其实根本就不要特判产地或者水果为空,直接用下标访问,如果没有创建,它就会自动帮你创建。

for(int i=1;i<=n;i++)
{
    cin>>fruit>>place>>w;
    vis[place][fruit]+=w;
}

AC代码精简版:

#include <bits/stdc++.h>
using namespace std;
int T,n,w;
string place,fruit;
map<string,map<string,int> >vis;
int main()
{
    ios::sync_with_stdio(false);
    cin>>T;
    while(T--)
    {
        cin>>n;
        vis.clear();
        for(int i=1;i<=n;i++)
        {
            cin>>fruit>>place>>w;
            vis[place][fruit]+=w;
        }
        for(auto i:vis)
        {
            string pl=i.first;
            printf("%s\n",pl.c_str());
            for(auto j:i.second)
            {
                string fr=j.first;
                int sumw=j.second;
                printf("   |----%s(%d)\n",fr.c_str(),sumw);
            }
        }
        if(T!=0)printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ljw_study_in_CSDN/article/details/105800800