Untitled

 avatar
Darin
plain_text
a year ago
2.1 kB
1
Indexable
Never
import java.util.*;

class Solution {
    static class Product {
        int price;
        boolean isBuy;
    }

    Product[] products = new Product[MAX_PRODUCTS];
    Map<String, List<Integer>> hashProduct = new HashMap<>();
    int cntProducts;
    static final int MAX_PRODUCTS = 30005;

    void init(int N) {
        cntProducts = 0;
        hashProduct.clear();
    }

    void addProduct(int mPrice, int tagNum, String[] tagName) {
        products[cntProducts] = new Product();
        products[cntProducts].price = mPrice;
        products[cntProducts].isBuy = false;

        List<String> tag = new ArrayList<>();
        for (int i = 0; i < tagNum; i++) {
            tag.add(tagName[i]);
            hashProduct.computeIfAbsent(tagName[i], k -> new ArrayList<>()).add(cntProducts);
        }
        Collections.sort(tag);
        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.get(i) + " " + tag.get(j) + " " + tag.get(k);
                    hashProduct.computeIfAbsent(s, key -> new ArrayList<>()).add(cntProducts);
                }
            }
        }
        cntProducts++;
    }

    int buyProduct(String tag1, String tag2, String tag3) {
        List<String> tag = new ArrayList<>();
        tag.add(tag1);
        tag.add(tag2);
        tag.add(tag3);
        Collections.sort(tag);
        String s = tag.get(0) + " " + tag.get(1) + " " + tag.get(2);
        int res = -1;
        for (int id : hashProduct.getOrDefault(s, new ArrayList<>())) {
            if (!products[id].isBuy && (res == -1 || products[id].price < products[res].price)) {
                res = id;
            }
        }
        if (res == -1)
            return -1;
        else {
            products[res].isBuy = true;
            return products[res].price;
        }
    }

    void adjustPrice(String tag1, int changePrice) {
        for (int id : hashProduct.getOrDefault(tag1, new ArrayList<>())) {
            products[id].price += changePrice;
        }
    }
}