• + 0 comments

    Cpp solution (some tle test cases i dont know how to optimize, the complexity maybe O(n * m * n))

    #include<bits/stdc++.h>
    using namespace std;
    
    #define Max 100000
    
    void dijsktra(int n, vector<int> &fishtypes, vector<vector<pair<int, int>>> &adj, vector<vector<int>> &totalweight)
    {
        //create set of [distance, shop, types of fish]
        set<pair<int, pair<int, int>>> st;
        st.insert({0, {0, fishtypes[0]}});
        while(st.size() != 0)
        {
            pair<int, pair<int, int>> node = *(st.begin());
            st.erase(st.begin());
            int curdist = node.first;
            int curshop = node.second.first;
            int curTypeOfFish = node.second.second;
            //we will skip when we already go to that shop with the same types of fish collected but with smaller total weight
            if(curdist >= totalweight[curshop][curTypeOfFish]) continue;
            totalweight[curshop][curTypeOfFish] = curdist;
            for(int i = 0; i < adj[curshop].size(); i++)
            {
                int newdist = curdist + adj[curshop][i].second;
                int nextshop = adj[curshop][i].first;
                int newtype = curTypeOfFish | fishtypes[nextshop];
                pair<int, pair<int, int>> nextnode(newdist, {nextshop, newtype});
                st.insert(nextnode);
            }
        }
    }
    int main()
    {
        int n, m, k;
        cin >> n >> m >> k;
        vector<int> fishtypes(n, 0);
        //bit-masking for types of fish sold by i-th shop
        for(int i = 0; i < n; i++)
        {
            int x;
            cin >> x;
            for(int j = 0; j < x; j++)
            {
                int type;
                cin >> type;
                fishtypes[i] = fishtypes[i] | (1 << (type - 1));
            }
        }
        //create adj list
        vector<vector<pair<int, int>>> adj(n, vector<pair<int, int>>());
        for(int i = 0; i < m; i++)
        {
            int shop1;
            int shop2;
            int weight;
            cin >> shop1 >> shop2 >> weight;
            adj[shop1 - 1].push_back({shop2 - 1, weight});
            adj[shop2 - 1].push_back({shop1 - 1, weight});
        }
        vector<bool> visited(n, false);
        vector<vector<int>> totalweight(n, vector<int>(1 << k, INT_MAX));
        dijsktra(n, fishtypes, adj, totalweight);
        int res = INT_MAX;
        for(int i = 0; i < (1 << k); i++)
        {
            if(totalweight[n - 1][i] == INT_MAX) continue;
            for(int j = i; j < (1 << k); j++)
            {
                if(totalweight[n - 1][j] == INT_MAX) continue;
                if((i | j) == (1 << k) - 1)
                {
                    res = min(res, max(totalweight[n - 1][i], totalweight[n - 1][j]));
                }
            }
        }
        cout << res;
        return 0;
    }