水果
Problem 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)
题目明显涉及到了两对关联,产地和品种的关联,品种和数量的关联,那么可以使用二维map将其储存一起。二维map中键为一个基本数据类型,值为一个map容器,这个值是容器又可以装入其它许多键值对,那么相当于二维map中一个键对应到了多组“值”!(一维map一个键只能对应一个值,例如A关联于B、C、D,如果A作为键那么值只能从BCD中选一个,只能建立一组关联。但是可以令B、C、D作为键,A作为它们的值,这样三组关联全部建立!)
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
using namespace std;
map<string,map<string ,int> > w; //要注意空格!否则>>相连会编译错误
int n, m;
int main()
{
cin >> n;
while (n--)
{
w.clear(); //清空map
cin >> m;
while (m--)
{
string s1, s2; int tmp;
cin >> s1 >> s2 >> tmp;
w[s2][s1] += tmp;
}
for (map<string, map<string, int> >::iterator it1 = w.begin(); it1 != w.end(); it1++)
{
cout << it1->first << endl;
for (map<string, int>::iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++)
cout << " |----" << it2->first << '(' << it2->second << ')' << endl;
}
if (n != 0) //注意题目的要求
cout << endl;
}
return 0;
}