/*
题目描述:给出两个栈A和B,一共有3中操作:
push X y 在X栈中加入y
pop X 在X栈中删掉栈顶元素并输出
merge X Y 将X栈和Y栈按照进入的顺序重组成为一个新的栈,并让这个栈代替X,同时将Y清空
一共有操作n( 0 < n < 1e5),要求按照顺序输出pop的结果
思路:利用对顶的双栈来解决问题,双栈的实现用链表,假设原来的状态是这样的
-----+++
减号为栈A元素,+为栈B元素,A的栈顶是最左边的-的向右一个,B的栈顶是最右边+的向左一个,那么
合并后-------+
在B中加入新元素后 -----++++
删掉A中元素 比较A的栈顶和栈底元素加入的时机,加入晚的删掉
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#include<bitset>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps=1e-6;
const int maxn = 2e5 + 50;
int cnt , lef[maxn] , rig[maxn];
struct node
{
int x , time;
}a[maxn];
void init(int & al , int & ar , int & bl , int & br)
{
ar = 100000;
bl = ar + 1;
al = ar;
br = bl;
cnt = 0;
for(int i = 1 ; i<= 200000;i++){
lef[i] = i - 1;
rig[i] = i + 1;
a[i].time = -INF;
}
}
void pushA(int & al , int & ar , int & bl , int & br , int x)
{
node st;
st = {x , ++cnt};
a[al] = st;
al = lef[al];
}
void pushB(int & al , int & ar , int & bl , int & br , int x)
{
node st;
st = {x , ++cnt};
a[br] = st;
br = rig[br];
}
void merge_B_to_A(int & al , int & ar , int & bl , int & br)
{
ar = lef[br];
bl = br = rig[ar];
}
void merge_A_to_B(int & al , int & ar , int & bl , int & br)
{
bl = rig[al] ;
al = ar = lef[bl];
}
int popA(int & al , int & ar , int & bl , int & br)
{
int res , alef = rig[al];
if(a[alef].time >= a[ar].time){
res = a[alef].x;
a[alef].time = -INF;
al = alef;
}
else{
res = a[ar].x;
a[ar].time = -INF;
ar = lef[ar];
rig[ar] = bl;
lef[bl] = ar;
}
return res;
}
int popB(int & al , int & ar , int & bl , int & br)
{
int res , brig = lef[br];
if(a[bl].time <= a[brig].time){
res = a[brig].x;
a[brig].time = -INF;
br = brig;
}
else{
res = a[bl].x;
a[bl].time = -INF;
bl = rig[bl];
rig[ar] = bl;
lef[bl] = ar;
}
return res;
}
int main()
{
int al , ar , bl , br , n , kase = 0;
char s[30];
while(scanf("%d", &n) != EOF){
if(n == 0) break;
init(al , ar , bl , br);
int x , res;
printf("Case #%d:\n",++kase);
for(int _ = 0 ; _ < n ; _++){
scanf("%s", s);
if(strcmp(s , "push") == 0){
scanf("%s %d",s , &x);
if(s[0] == 'A'){
pushA(al , ar , bl , br , x);
}
else{
pushB(al , ar , bl , br , x);
}
}
else if(strcmp(s , "pop") == 0){
scanf("%s",s);
if(s[0] == 'A'){
res = popA(al , ar , bl , br);
}
else{
res = popB(al , ar , bl , br);
}
printf("%d\n",res);
}
else if(strcmp(s , "merge") == 0){
scanf("%s",s);
scanf("%s",s);
if(s[0] == 'A'){
merge_A_to_B(al , ar , bl , br);
}
else{
merge_B_to_A(al , ar , bl , br);
}
}
}
}
return 0;
}
Hdu 5815 Joint stack 链式对顶栈
最新推荐文章于 2023-07-11 13:06:21 发布