Untitled

 avatar
unknown
c_cpp
a year ago
1.9 kB
3
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 t2.time < t1.time;
    }
};

class Twitter {
public:

int time = 0;
int selfId=0;
unordered_map<int,User> map;
priority_queue<Tweet,vector<Tweet>,Comp> q;
    Twitter() {
        
    }
    
    void postTweet(int userId, int tweetId) {
     if(!selfId)   selfId = userId;
     if(map.find(selfId)==map.end()){
        User u(selfId);
        map[selfId] = u;
     }
        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[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) {
        User u(followerId);
        u.follow(followeeId);
    }
    
    void unfollow(int followerId, int followeeId) {
  
        map[followerId].unfollow(followeeId);
    }
};
Editor is loading...
Leave a Comment