Untitled
unknown
c_cpp
a year ago
2.2 kB
8
Indexable
class Tweet { public: int tweet_id; int user_id; int time; Tweet(int userId,int tweetId,int time): user_id(userId),tweet_id(tweetId),time(time){} }; class User { public: int user_id; unordered_set<int> followees; User(int userId): user_id(userId){} void follow(int followeeId){ followees.insert(followeeId); } void unfollow(int followeeId){ followees.erase(followees.find(followeeId)); } bool isFollowerOf(int followeeId){ return followees.find(followeeId)!=followees.end(); } }; struct Comp{ bool operator() (const Tweet &t1,const Tweet &t2){ return t1.time < t2.time; } }; class Twitter { public: int time; int selfId; unordered_map<int,User> map; priority_queue<Tweet,vector<Tweet>,Comp> q; Twitter() { time = 0; selfId = 0; } void postTweet(int userId, int tweetId) { if (!selfId) selfId = userId; if (map.find(selfId) == map.end()) { map.insert({selfId, User(selfId)}); } Tweet t(userId, tweetId, time); time++; q.push(t); } vector<int> getNewsFeed(int userId) { vector<int> tweets; queue<Tweet> q2; while(!q.empty() && tweets.size()!=10){ Tweet t = q.top(); q.pop(); if (map.find(userId) != map.end() && (map.at(userId).isFollowerOf(t.user_id) || t.user_id == selfId)){ tweets.push_back(t.tweet_id); } q2.push(t); } while(q2.empty()==false){ q.push(q2.front()); q2.pop(); } return tweets; } void follow(int followerId, int followeeId) { if(map.find(followerId)==map.end()){ User u(followerId); map.insert({followerId,u}); } else{ (*map.find(followerId)).second.follow(followeeId); } } void unfollow(int followerId, int followeeId) { if(map.find(followerId)!=map.end()){ (*map.find(followerId)).second.unfollow(followeeId); } } };
Editor is loading...
Leave a Comment