hash,使用stl map ac。学了find_if等强大的东西,第一次使用stl模板。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <map> 6 #include <vector> 7 using namespace std; 8 9 #define NAMENUM 25 10 11 typedef struct fruit_st { 12 char name[NAMENUM]; 13 char produce[NAMENUM]; 14 bool operator < (const fruit_st &a) const { 15 if (strcmp(produce, a.produce)) 16 return strcmp(produce, a.produce)>0 ? false : true; 17 else 18 return strcmp(name, a.name)>0 ? false : true; 19 } 20 } fruit_st; 21 22 class map_finder { 23 public: 24 map_finder(const fruit_st a) { 25 strcpy(fruit.name, a.name); 26 strcpy(fruit.produce, a.produce); 27 } 28 bool operator ()(const map<fruit_st, int>::value_type &pair) { 29 if (strcmp(fruit.name, pair.first.name)==0 && strcmp(fruit.produce, pair.first.produce)==0) 30 return true; 31 else 32 return false; 33 } 34 private: 35 fruit_st fruit; 36 }; 37 38 int main() { 39 map<fruit_st, int> sale_info; 40 map<fruit_st, int>::iterator iter; 41 fruit_st fruit; 42 int case_n, n, num; 43 44 scanf("%d", &case_n); 45 46 while (case_n--) { 47 scanf("%d", &n); 48 while (n--) { 49 scanf("%*c%s %s %d", fruit.name, fruit.produce, &num); 50 51 iter = find_if(sale_info.begin(), sale_info.end(), map_finder(fruit)); 52 if (iter == sale_info.end()) { 53 sale_info.insert(make_pair(fruit, num)); 54 //sale_info[fruit] = num; 55 }else 56 iter->second += num; 57 } 58 for (map<fruit_st, int>::iterator ii=sale_info.begin(); ii!=sale_info.end(); ++ii) { 59 if (ii != sale_info.begin()) { 60 if (strcmp(ii->first.produce, iter->first.produce)) 61 printf("%s\n", ii->first.produce); 62 printf(" |----%s(%d)\n", ii->first.name, ii->second); 63 } else { 64 printf("%s\n", ii->first.produce); 65 printf(" |----%s(%d)\n", ii->first.name, ii->second); 66 } 67 iter = ii; 68 } 69 sale_info.clear(); 70 if (case_n) 71 printf("\n"); 72 } 73 74 return 0; 75 }