这段时间重温一下C++编程
1125. 最小的必要团队
状态压缩DP
状态压缩就是使用某种方法,简明扼要地以最小代价来表示某种状态,通常是用一串01数字(二进制数)来表示各个点的状态。这就要求使用状态压缩的对象的点的状态必须只有两种,0 或 1
class Solution {
public:
vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) {
unordered_map<string, int> map;
int m =req_skills.size();
for (int i =0 ;i<m;i++){
map[req_skills[i]]=i;
}
int n = people.size();
vector<int> evo(n,0);
for(int i =0 ;i<n;i++){
for (auto &x :people[i])
evo[i] |= 1<<map[x];
}
vector<vector<int>> dp(1<<m);
int tmpnum=0;
for(int i =0;i<n;i++){
if (evo[i] ==0 )
continue;
for (int j =0;j<=tmpnum;++j){
if(j && dp[j].empty())
continue;
int newnum =j|evo[i];
if (dp[newnum].empty() || dp[newnum].size()>dp[j].size()+1){
dp[newnum]=dp[j];
dp[newnum].push_back(i);
}
}
tmpnum |=evo[i];
}
return dp[(1<<m) -1 ];
}
};
743. 网络延迟时间https://leetcode-cn.com/problems/smallest-sufficient-team/)
用C++ 重写 一下Dijkstra
熟悉一下优先队列
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
vector<vector<pair<int,int>>> tab(n);
for(auto &i :times){
tab[i[0]-1].push_back({i[2],i[1]-1});
}
vector<int> lis(n,INT_MAX-1);
vector<int> vist(n,0);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> que;
que.push({0,k-1});
lis[k-1]=0;
while (!que.empty()){
auto top = que.top();
int node= top.second;
que.pop();
if (vist[node]==0){
for(auto &x :tab[node]){
if (vist[x.second]==0 && lis[node]+x.first<lis[x.second]){
lis[x.second] =lis[node]+x.first;
que.push({lis[x.second],x.second});
}
}
vist[node] =1;
}
}
int ans = *max_element(lis.begin(), lis.end());
return ans == INT_MAX-1 ? -1 : ans;
}
};