We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Cpp solution (some tle test cases i dont know how to optimize, the complexity maybe O(n * m * n))
#include<bits/stdc++.h>usingnamespacestd;#define Max 100000voiddijsktra(intn,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());intcurdist=node.first;intcurshop=node.second.first;intcurTypeOfFish=node.second.second;//we will skip when we already go to that shop with the same types of fish collected but with smaller total weightif(curdist>=totalweight[curshop][curTypeOfFish])continue;totalweight[curshop][curTypeOfFish]=curdist;for(inti=0;i<adj[curshop].size();i++){intnewdist=curdist+adj[curshop][i].second;intnextshop=adj[curshop][i].first;intnewtype=curTypeOfFish|fishtypes[nextshop];pair<int,pair<int,int>>nextnode(newdist,{nextshop,newtype});st.insert(nextnode);}}}intmain(){intn,m,k;cin>>n>>m>>k;vector<int>fishtypes(n,0);//bit-masking for types of fish sold by i-th shopfor(inti=0;i<n;i++){intx;cin>>x;for(intj=0;j<x;j++){inttype;cin>>type;fishtypes[i]=fishtypes[i]|(1<<(type-1));}}//create adj listvector<vector<pair<int,int>>>adj(n,vector<pair<int,int>>());for(inti=0;i<m;i++){intshop1;intshop2;intweight;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);intres=INT_MAX;for(inti=0;i<(1<<k);i++){if(totalweight[n-1][i]==INT_MAX)continue;for(intj=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;return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Synchronous Shopping
You are viewing a single comment's thread. Return to all comments →
Cpp solution (some tle test cases i dont know how to optimize, the complexity maybe O(n * m * n))