原题链接:Leetcode 1311. 获取你好友已观看的视频
map自定义排序 参考:C++容器map可以排序吗?
static bool cmp(const pair<string,int> &a,const pair<string,int> &b)
{
if(a.second==b.second) return a.first<b.first;
return a.second<b.second;
}
map<string,int> mp;
vector<pair<string,int>> s(mp.begin(),mp.end());
sort(s.begin(),s.end(),cmp);
DFS
class Solution {
public:
static bool cmp(const pair<string,int> &a,const pair<string,int> &b)
{
if(a.second==b.second) return a.first<b.first;
return a.second<b.second;
}
map<string,int> mp;
vector<int> visit;
void dfs(int now,int cnt,int level,vector<vector<string>>& watchedVideos, vector<vector<int>>& friends)
{
if(cnt==level) return ;
for(auto x:friends[now])
{
if(!visit[x] || visit[x]>cnt+1)
{
visit[x]=cnt+1;
dfs(x,cnt+1,level,watchedVideos,friends);
}
}
}
vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) {
int n=friends.size();
visit.resize(n);
visit[id]=-1;
dfs(id,0,level,watchedVideos,friends);
vector<string> res;
for(int i=0;i<n;i++)
{
if(visit[i]==level)
{
for(auto x:watchedVideos[i]) mp[x]++;
}
}
vector<pair<string,int>> s(mp.begin(),mp.end());
sort(s.begin(),s.end(),cmp);
for(auto x:s) res.push_back(x.first);
return res;
}
};
BFS
class Solution {
public:
static bool cmp(const pair<string,int> &a,const pair<string,int> &b)
{
if(a.second==b.second) return a.first<b.first;
return a.second<b.second;
}
map<string,int> mp;
vector<int> visit;
vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) {
int n=friends.size();
visit.resize(n);
queue<int> q; q.push(id);
while(!q.empty())
{
int now=q.front(); q.pop();
for(auto x:friends[now])
{
if((!visit[x] || visit[x]>visit[now]+1) && x!=id)
{
visit[x]=visit[now]+1;
if(visit[x]<level) q.push(x);
}
}
}
vector<string> res;
for(int i=0;i<n;i++)
{
if(visit[i]==level)
{
for(auto x:watchedVideos[i]) mp[x]++;
}
}
vector<pair<string,int>> s(mp.begin(),mp.end());
sort(s.begin(),s.end(),cmp);
for(auto x:s) res.push_back(x.first);
return res;
}
};