HDU - 1263 -- 水果【排序升级版,map VS pair自带优先级】

水果
Description

夏天来了~~ 好开心啊,呵呵,好多好多水果 ~~
Joe经营着一个不大的水果店.他认为生存之道就是经营最受顾客欢迎的水果.现在他想要一份水果销售情况的明细表,这样Joe就可以很容易掌握所有水果的销售情况了.

Input

第一行正整数N(0<N<=10)表示有N组测试数据.
每组测试数据的第一行是一个整数M(0<M<=100),表示工有M次成功的交易.其后有M行数据,每行表示一次交易,由水果名称(小写字母组成,长度不超过80),水果产地(小写字母组成,长度不超过80)和交易的水果数目(正整数,不超过100)组成.

Output

对于每一组测试数据,请你输出一份排版格式正确(请分析样本输出)的水果销售情况明细表.这份明细表包括所有水果的产地,名称和销售数目的信息.水果先按产地分类,产地按字母顺序排列;同一产地的水果按照名称排序,名称按字母顺序排序.
两组测试数据之间有一个空行.最后一组测试数据之后没有空行.

Sample Input

1
5
apple shandong 3
pineapple guangdong 1
sugarcane guangdong 1
pineapple guangdong 3
pineapple guangdong 1

Sample Output

guangdong
|----pineapple(5)
|----sugarcane(1)
shandong
|----apple(3)

pair+vector+sort

本题处理输出有点麻烦,当然可以用结构体来存结构,然后判断地区是否是相同的即可。这里我用的pair,因为pair自带优先级。

AC代码
#include<iostream>
#include<cstdio>
#include<utility>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
typedef pair<string,string> pl;
typedef pair<pl,int>  pll;
int main(){
	int n,m,val;
	string fruit,origin;
	cin>>n;
	for(int j;j<n;j++){
		cin>>m;
		vector<pll> v;
		while(m--){
			cin>>fruit>>origin>>val;
			v.push_back(pll(pl(origin,fruit),val));
		}
		sort(v.begin(),v.end());
		vector<pll>	ans;
		int sum=v[0].second;
		for(int i=1;i<v.size();i++){
			if(v[i-1].first == v[i].first)	sum+=v[i].second;
			else{
				ans.push_back(pll(v[i-1].first,sum));
				sum = v[i].second;
			}
		}
		ans.push_back(pll(v[v.size()-1].first,sum));
		
		cout<<ans[0].first.first<<endl;
		for(int i=0;i<ans.size()-1;i++){
			pll cur = ans[i];
			pll next = ans[i+1];
			if(next.first.first == cur.first.first)//产地相同 
				cout<<"   |----"<< cur.first.second <<"("<< cur.second <<")"<<endl;
			else{//产地不同 
				cout<<"   |----"<< cur.first.second <<"("<< cur.second <<")"<<endl;
				cout<<next.first.first<<endl;
			}
		}
		int num=ans.size()-1;
		cout<<"   |----"<< ans[num].first.second <<"("<< ans[num].second <<")"<<endl;
		if(j<n-1)	puts("");	
	}
	return 0;
}
map解法

map是自动排序的一个容器,利用这一点,我们用二维map写起来很方便,代码也非常的通俗易懂,如果要从大到小输出,我们可以用rbegin 和 rend这两个方法来写。

AC代码
#include<iostream>
#include<cstdio>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	int t,n,val;
	cin>>t;
	string fruit,origin;
	map<string,map<string,int> >mp;
	for(int i=0;i<t;i++){
		cin>>n;
		mp.clear();
		for(int i=0;i<n;i++){
			cin>>fruit>>origin>>val;
			mp[origin][fruit]+=val;
		}
		for(auto it:mp){
			cout<<it.first<<endl;
			for(auto it1: it.second){
				cout<<"   |----"<< it1.first <<"("<< it1.second <<")"<<endl;
			}
		}
		if(i<t-1)	puts("");
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星空皓月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值