您的位置:首页 > 其它

HDU 4699 Editor( stack)

2013-08-23 16:07 447 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4699

刚看见这个题目以为又是什么线段树之类,后来发现链表可以模拟,就用链表模拟一下,不过是在数组上模拟的链表,这样会比真正的链表

操作方便一些,速度可能也快一些,而且涉及的都是下标号,不容易出错,但是用链表写还是复杂一些,毕竟链表的操作比较烦!

所有操作O(1)完成!

后来发现操作都在cursor这里,所有直接用两个栈来模拟

然后维护左边这个栈的一个和和当前位置前面和的一个最大值,所有操作都是O(1)完成

下面给出两种方法的代码:

链表模拟:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define maxn 1500000
struct node{
int pre,next;
int value;
}po[maxn];
int n,pos;
int plus1[maxn],ans[maxn],num,cur;
char str[10];
int moveleft(){
if(po[cur].pre!=-1) po[cur].value=po[po[cur].pre].value,cur=po[cur].pre,num--;
return 0;
}
int moveright(){
if(po[cur].next!=-1){
po[cur].value=po[po[cur].next].value,cur=po[cur].next;
plus1[num]=plus1[num-1]+po[po[cur].pre].value;
if(num==1 || plus1[num]>=ans[num-1]) ans[num]=plus1[num];
else ans[num]=ans[num-1];
num++;
}
return 0;
}
int insert(int v){//保证光标位置一定是空的
po[cur].value=v;
po[pos].next=po[cur].next,po[pos].pre=cur;
if(po[cur].next!=-1){
po[po[cur].next].pre=pos;
po[cur].next=pos;
}
else{
po[cur].next=pos,po[pos].next=-1;
}
cur=pos++;
plus1[num]=plus1[num-1]+po[po[cur].pre].value;
if(num==1 || plus1[num] >= ans[num-1]) ans[num]=plus1[num];
else
ans[num]=ans[num-1];
num++;
return 0;
}
int del(){
if(po[cur].pre==-1) return 0;
if(po[po[cur].pre].pre==-1){
po[cur].pre=-1;
num--;
return 0;
}
po[po[po[cur].pre].pre].next=cur;
po[cur].pre=po[po[cur].pre].pre;
num--;
return 0;
}
int main(){
int i,j,k,v;
while(scanf("%d",&n)!=EOF){
num=1;plus1[0]=0,ans[0]=0;
pos=2,cur=0;
po[0].pre=-1,po[0].next=-1;
for(i=0;i<n;i++){
scanf("%s",str);
switch(str[0]){
case 'I':scanf("%d",&k);insert(k);break;
case 'L':moveleft();break;
case 'R':moveright();break;
case 'D':del();break;
case 'Q':scanf("%d",&k);printf("%d\n",ans[k]);break;
}
}
}
return 0;
}


STL栈:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <stack>
using namespace std;
#define maxn 1100000
stack<int> A,B;
int n,num=1;
char str[10];
int plus1[maxn],ans[maxn];
int moveleft(){
if(!A.empty()) B.push(A.top()),A.pop(),num--;
return 0;
}
int moveright(){
if(!B.empty()){
int k=B.top();
B.pop();
A.push(k);
plus1[num]=plus1[num-1]+k;
if(num==1 || plus1[num]>=ans[num-1]) ans[num]=plus1[num];
else ans[num]=ans[num-1];
num++;
}
return 0;
}
int insert(int k){
A.push(k);
plus1[num]=plus1[num-1]+k;
if(num==1 || plus1[num]>=ans[num-1]) ans[num]=plus1[num];
else ans[num]=ans[num-1];
num++;
return 0;
}
int del(){
if(!A.empty()) A.pop(),num--;
return 0;
}
int main(){
int i,j,k;
while(scanf("%d",&n)!=EOF){
num=1,ans[0]=0,plus1[0]=0;
while(!A.empty()) A.pop();
while(!B.empty()) B.pop();
for(i=0;i<n;i++){
scanf("%s",str);
switch(str[0]){
case 'I':scanf("%d",&k);insert(k);break;
case 'L':moveleft();break;
case 'R':moveright();break;
case 'D':del();break;
case 'Q':scanf("%d",&k);printf("%d\n",ans[k]);break;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: