您的位置:首页 > 其它

HDU 5818 多校第七场 1010 Joint Stacks (线段树)

2016-08-09 17:17 344 查看
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=5818

题解说这题有O(n)的做法,并没有想到,只想到线段树的。

直接把两个栈同时在一颗线段树里操作,标记一下每个区间A有几个,B有几个,然后merge的时候区间更新一下,相互翻转一下个数。每次查询的时候,实际上就是查询最右边的A或者最右边的B,pop掉的空位就留着不要了。

复杂度O(nlogn),并不是很好。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define pb push_back
#define mp make_pair
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define calm (l+r)>>1
const int INF = 2139062143;

const int maxn=1e5+10;
int n,Case;
int num[maxn];
struct Seg{
int A[maxn<<2],B[maxn<<2],tag[maxn<<2];
inline void pushup(int rt){
A[rt]=A[rt<<1]+A[rt<<1|1];
B[rt]=B[rt<<1]+B[rt<<1|1];
}
inline void pushdown(int rt){
if(tag[rt]==1){
A[rt<<1]+=B[rt<<1];
B[rt<<1]=0;
A[rt<<1|1]+=B[rt<<1|1];
B[rt<<1|1]=0;
tag[rt<<1]=tag[rt<<1|1]=tag[rt];
tag[rt]=0;
}
else if(tag[rt]==2){
B[rt<<1]+=A[rt<<1];
A[rt<<1]=0;
B[rt<<1|1]+=A[rt<<1|1];
A[rt<<1|1]=0;
tag[rt<<1]=tag[rt<<1|1]=tag[rt];
tag[rt]=0;
}
}
void build(int l,int r,int rt){
A[rt]=B[rt]=tag[rt]=0;
if(l==r)return;
int m=calm;
build(lson);
build(rson);
}
void insert(int l,int r,int rt,int c,int x,int pos){
if(l==r){
if(c==0)A[rt]++;
else B[rt]++;
num[l]=x;
//printf("insert %d into %d\n",x,l);
return;
}
pushdown(rt);
int m=calm;
if(pos<=m){
insert(lson,c,x,pos);
}
else{
insert(rson,c,x,pos);
}
pushup(rt);
}
int query(int l,int r,int rt,int c){
if(l==r){
if(c==0)A[rt]--;
else B[rt]--;
int t=num[l];
num[l]=0;
return t;
}
pushdown(rt);
int m=calm,ans=0;
if(c==0){
if(A[rt<<1|1])ans=query(rson,c);
else ans=query(lson,c);
}
else{
if(B[rt<<1|1])ans=query(rson,c);
else ans=query(lson,c);
}
pushup(rt);
return ans;
}
void merge(int c){
tag[1]=c;
if(c==1){
A[1]+=B[1];B[1]=0;
}
else{
B[1]+=A[1];A[1]=0;
}
//printf("A=%d B=%d,tag[1]=%d\n",A[1],B[1],tag[1]);
}
}tree;
int main(){
//freopen("D://input.txt","r",stdin);
while(scanf("%d",&n)!=EOF&&n){
tree.build(1,n,1);
int now=0;//将要插入的位置
printf("Case #%d:\n",++Case);
for(int i=1;i<=n;i++){
char s[10];scanf("%s",s);
if(s[0]=='p'){
char c[3];scanf("%s",c);
if(s[1]=='u'){
int x;scanf("%d",&x);
if(c[0]=='A'){
tree.insert(1,n,1,0,x,++now);
}
else tree.insert(1,n,1,1,x,++now);
}
else{
if(c[0]=='A')printf("%d\n",tree.query(1,n,1,0));
else printf("%d\n",tree.query(1,n,1,1));
}
}
else if(s[0]=='m'){
char c[3];
scanf("%s",c);scanf("%s",c);
if(c[0]=='A'){//B A
tree.merge(2);
}
else{//A B
tree.merge(1);
}
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: