Untitled

 avatar
Darin
plain_text
2 years ago
2.2 kB
5
Indexable
#include<iostream>
#include<vector>
#include<string>
#include<unordered_map>
#include<algorithm>
  
#define MAX_PRODUCTS 30005
 
using namespace std;
 
struct Product{
    int price;
    bool isBuy;
} products[MAX_PRODUCTS];
int cntProducts; // tuong ung voi id san pham
 
/* hash table
key - tags
value - id products ~ cntProduct
*/
unordered_map<string, vector<int>> hashProduct; 
 
void init(int N)
{
    cntProducts = 0;
    hashProduct.clear();
}
 
void addProduct(int mPrice, int tagNum, char tagName[][10])
{
    products[cntProducts].price = mPrice;
    products[cntProducts].isBuy = false;
 
    // tao vector luu cac tag
    vector<string> tag;
    // push ten tag vao vector tag
    for (int i = 0; i < tagNum; i++) {
        tag.push_back(tagName[i]);
    }
    // sap xep tag tu a-z
    sort(tag.begin(), tag.end());
     
    // push tag don
    for (auto s:tag){
        hashProduct[s].push_back(cntProducts);
    }
    // hoan vi tag don de tao ra tag 3
    for (int i = 0; i < tag.size(); i++){
        for (int j = i+1; j < tag.size(); j++){
            for (int k = j+1; k < tag.size(); k++){
                string s = tag[i] + " " + tag[j] + " " + tag[k];
                //cout << "add " << s << endl;
                hashProduct[s].push_back(cntProducts); // push tag 3
            }
        }   
    }
 
    cntProducts++;
}   
 
int buyProduct(char tag1[], char tag2[], char tag3[])
{
    vector<string> tag;
    tag.push_back(tag1);
    tag.push_back(tag2);
    tag.push_back(tag3);
    sort(tag.begin(), tag.end());
    string s = tag[0] + " " + tag[1] + " " + tag[2];
    //cout << "buy " << s << endl;
    int res = -1;
    // tim cac sp co dung tag s
    for (auto id:hashProduct[s]){
        if (products[id].isBuy == false && (res == -1 || products[id].price < products[res].price)){
            res = id;
        }
    }
    if (res == -1) return -1; // khong mua duoc
    products[res].isBuy = true;
    return products[res].price;
}
 
void adjustPrice(char tag1[], int changePrice)
{
    for (auto id:hashProduct[tag1]){
        products[id].price += changePrice;
    }
}
Editor is loading...