度度熊学队列
解题思路
STL大法好。直接用deque,但是N的范围很大,如果直接开那么多的deque会爆内存,所以用map< int, deque< int>>,多组数据,记得清空map。
代码如下
#include #define INF 0x3f3f3f3fusing namespace std;typedef long long ll;inline int read(){ int res = 0, w = 0; char ch = 0; while(!isdigit(ch)){ w |= ch == '-', ch = getchar(); } while(isdigit(ch)){ res = (res << 3) + (res << 1) + (ch ^ 48); ch = getchar(); } return w ? -res : res;}const int N = 100005;map
> mp;int main(){ int n, q; while(scanf("%d%d", &n, &q)!= EOF){ for(int i = 1; i <= n; i ++) mp[i].clear(); for(int i = 1; i <= q; i ++){ int opt; opt = read(); if(opt == 1){ int u, w, val; u = read(), w = read(), val = read(); if(w) mp[u].push_back(val); else mp[u].push_front(val); } else if(opt == 2){ int u, w; u = read(), w = read(); if(!mp[u].empty()){ if(w){ printf("%d\n", mp[u].back()); mp[u].pop_back(); } else{ printf("%d\n", mp[u].front()); mp[u].pop_front(); } } else printf("-1\n"); } else { int u, v, w; u = read(), v = read(), w = read(); if(w) mp[u].insert(mp[u].end(), mp[v].rbegin(), mp[v].rend()); else mp[u].insert(mp[u].end(), mp[v].begin(), mp[v].end()); mp[v].clear(); } } } return 0;