erni_hax

multisets 2 X96044

Jan 14th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.37 KB | None | 0 0
  1.  14: #include <iostream>
  2.   15: #include <vector>
  3.   16: #include <algorithm>
  4.   17: using namespace std;
  5.   18:
  6.   19: typedef vector<string> Set;
  7.   20: typedef struct{string id; int occur;} Element;
  8.   21: typedef vector<Element> Multiset;
  9.   22:
  10.   23: Set read_set(){
  11.   24:     int n;
  12.   25:     cin >> n;
  13.   26:     Set s(n);
  14.   27:     for (int i = 0; i < n; ++i) cin >> s[i];
  15.   28:     return s;
  16.   29: }
  17.   30:
  18.   31: bool empty(const Set& s){
  19.   32:     return s.size() == 0;
  20.   33: }
  21.   34:
  22.   35: void write_multiset(const Multiset& m){
  23.   36:     int n = m.size();
  24.   37:     for (int i=0; i < n; ++i){
  25.   38:         cout << "(" << m[i].id << " , " << m[i].occur << ")" << endl;
  26.   39:     }
  27.   40: }
  28.   41:
  29.   42: Multiset multi_union(Multiset& m, Set& s1){
  30.   43:     int ss1 = s1.size();
  31.   44:     for(int set_counter = 0; set_counter < ss1; set_counter++) { //We loop through the set for the elements
  32.   45:         int is_element_found = false; //We search if element already exists
  33.   46:         int sm = m.size();
  34.   47:         for(int multiset_counter = 0; multiset_counter < sm && !is_element_found; multiset_counter++) {
  35.   48:             if(m.at(multiset_counter).id == s1.at(set_counter)) { //if it exists we increment the counter
  36.   49:                 is_element_found = true;
  37.   50:                 m.at(multiset_counter).occur++;
  38.   51:             }
  39.   52:         }
  40.   53:         //If we couldnt find the element we push a new one
  41.   54:         if(!is_element_found) {
  42.   55:             Element element;
  43.   56:             element.id = s1.at(set_counter);
  44.   57:             element.occur = 1;
  45.   58:             m.push_back(element);
  46.   59:         }
  47.   60:     }
  48.   61:     return m; //Redundant return.
  49.   62: }
  50.   63: bool comp(const Element &a, const Element &b) {
  51.   64:     return a.id < b.id; //we compare the names in ascending order
  52.   65: }
  53.   66: int main(){
  54.   67:     Multiset multi_set;
  55.   68:     Set load_set;
  56.   69:     while(!empty((load_set = read_set()))) //We read next set
  57.   70:         multi_union(multi_set, load_set); //We apply the function while theres sets
  58.   71:
  59.   72:     multi_union(multi_set, load_set); //We apply the function for the last set
  60.   73:     std::sort(multi_set.begin(), multi_set.end(), comp); //we sort elements names with a custom function
  61.   74:     write_multiset(multi_set); //We write the result
  62.   75:     return 0;
  63.   76: }
Add Comment
Please, Sign In to add comment