import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
public class Twitter {
private Map<Integer, Tweet> twitter;
private Map<Integer, Set<Integer>> followings;
private static int timestamp = 0;
private static PriorityQueue<Tweet> maxHeap;
public Twitter() {
followings = new HashMap<>();
twitter = new HashMap<>();
maxHeap = new PriorityQueue<>((o1, o2) -> -o1.timestamp + o2.timestamp);
}
public void postTweet(int userId, int tweetId) {
timestamp++;
if (twitter.containsKey(userId)) {
Tweet oldHead = twitter.get(userId);
Tweet newHead = new Tweet(tweetId, timestamp);
newHead.next = oldHead;
twitter.put(userId, newHead);
} else {
twitter.put(userId, new Tweet(tweetId, timestamp));
}
}
public List<Integer> getNewsFeed(int userId) {
maxHeap.clear();
if (twitter.containsKey(userId)) {
maxHeap.offer(twitter.get(userId));
}
Set<Integer> followingList = followings.get(userId);
if (followingList != null && followingList.size() > 0) {
for (Integer followingId : followingList) {
Tweet tweet = twitter.get(followingId);
if (tweet != null) {
maxHeap.offer(tweet);
}
}
}
List<Integer> res = new ArrayList<>(10);
int count = 0;
while (!maxHeap.isEmpty() && count < 10) {
Tweet head = maxHeap.poll();
res.add(head.id);
if (head.next != null) {
maxHeap.offer(head.next);
}
count++;
}
return res;
}
public void follow(int followerId, int followeeId) {
if (followeeId == followerId) {
return;
}
Set<Integer> followingList = followings.get(followerId);
if (followingList == null) {
Set<Integer> init = new HashSet<>();
init.add(followeeId);
followings.put(followerId, init);
} else {
if (followingList.contains(followeeId)) {
return;
}
followingList.add(followeeId);
}
}
public void unfollow(int followerId, int followeeId) {
if (followeeId == followerId) {
return;
}
Set<Integer> followingList = followings.get(followerId);
if (followingList == null) {
return;
}
followingList.remove(followeeId);
}
private class Tweet {
private int id;
private int timestamp;
private Tweet next;
public Tweet(int id, int timestamp) {
this.id = id;
this.timestamp = timestamp;
}
}
}
class Solution {
List<String> res = new LinkedList<>();
char[] c;
public String[] permutation(String s) {
c = s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);
}
void dfs(int x) {
if(x == c.length - 1) {
res.add(String.valueOf(c));
return;
}
HashSet<Character> set = new HashSet<>();
for(int i = x; i < c.length; i++) {
if(set.contains(c[i])) continue;
set.add(c[i]);
swap(i, x);
dfs(x + 1);
swap(i, x);
}
}
void swap(int a, int b) {
char tmp = c[a];
c[a] = c[b];
c[b] = tmp;
}
}