给一份水果出售记录,要求整理出一份排版格式正确的水果销售情况明细表。
输入格式
第一行是一个整数N(0<N≤1000),表示工有N次成功的交易。其后有N行数据,每行表示一次交易,由水果名称(小写字母组成,长度不超过100),水果产地(小写字母组成,长度不超过100)和交易的水果数目(正整数,不超过1000)组成。
输出格式
请你输出一份排版格式正确(请分析样本输出)的水果销售情况明细表。这份明细表包括所有水果的产地、名称和销售数目的信息。水果先按产地分类,产地按字母顺序排列;同一产地的水果按照名称排序,名称按字母顺序排序。
样例输入
5
apple shandong3
pineapple guangdong 1
sugarcane guangdong 1
pineapple guangdong3
pineapple guangdong 1
样例输出
guangdong
|----pineapple(5)
|----sugarcane(1)
shandong
|----apple(3)
此题有两种思路,第一种是二维map,第二种是struct+map。
第一种如下:
#include<iostream>
#include<map>
using namespace std;
map<string, map<string, int> > m; //定义二维map
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string a, b;
int l;
cin >> a >> b >> l;
m[b][a] += l; //注意不能写成m[b][a]=l,这样会将上一个值覆盖,要写成累加
}
for (map<string, map<string, int> >::iterator t1 = m.begin(); t1 != m.end();t1++) {
cout << t1->first << endl;
for ( map<string, int>::iterator t2 = (t1->second).begin(); t2 != (t1->second).end(); t2++) {
cout << " |----" << t2->first << "(" << t2->second << ")"<<endl;
}
}
return 0;
}
第二种如下:
#include<iostream>
#include<map>
using namespace std;
struct sg { //将水果名称和水果产地写成一个结构体
string a;
string b;
bool operator <(const sg& l) const { //map结合结构体时要重新定义<
if (b == l.b) {
return a < l.a;
}
else {
return b < l.b;
}
}
};
sg s[1000];
int main() {
int n;
cin >> n;
map<sg, int> qq;
for (int i = 0; i < n; i++) {
cin >> s[i].a >> s[i].b;
int o;
cin >> o;
qq[s[i]] = qq[s[i]]+o;
}
for (map<sg, int>::iterator t = qq.begin(); t != qq.end();) {
string q = t->first.b;
cout << t->first.b<<endl;
cout << " |----" << t->first.a << "(" << t->second << ")" << endl;
t++;
for (t; t != qq.end(); t++) {
if (q!= t->first.b) {
break;
}
else {
cout << " |----" << t->first.a << "(" << t->second << ")" << endl;
}
}
}
return 0;
}
显然第一种比较简单。