Problem UVA12657-Boxes in a Line(数组模拟双链表)

时间:2023-03-09 17:36:09
Problem UVA12657-Boxes in a Line(数组模拟双链表)

Problem UVA12657-Boxes in a Line

Accept: 725  Submit: 9255

Time Limit: 1000 mSec

Problem UVA12657-Boxes in a Line(数组模拟双链表) Problem Description

You have n boxes in a line on the table numbered 1...n from left to right. Your task is to simulate 4 kinds of commands:

• 1 X Y : move box X to the left to Y (ignore this if X is already the left of Y )

• 2 X Y : move box X to the right to Y (ignore this if X is already the right of Y )

• 3 X Y : swap box X and Y

• 4: reverse the whole line.

Commands are guaranteed to be valid, i.e. X will be not equal to Y . For example, if n = 6, after executing 1 1 4, the line becomes 2 3 1 4 5 6. Then after executing 2 3 5, the line becomes 2 1 4 5 3 6. Then after executing 3 1 6, the line becomes 2 6 4 5 3 1. Then after executing 4, then line becomes 1 3 5 4 6 2

Problem UVA12657-Boxes in a Line(数组模拟双链表) Input

There will be at most 10 test cases. Each test case begins with a line containing 2 integers n, m (1 ≤ n,m ≤ 100,000). Each of the following m lines contain a command.

Problem UVA12657-Boxes in a Line(数组模拟双链表) Output

For each test case, print the sum of numbers at odd-indexed positions. Positions are numbered 1 to n from left to right.

Problem UVA12657-Boxes in a Line(数组模拟双链表) Sample Input

6 4 1 1 4 2 3 5 3 1 6 4 6 3 1 1 4 2 3 5 3 1 6 100000 1 4

Problem UVA12657-Boxes in a Line(数组模拟双链表) Sample output

Case 1: 12

Case 2: 9

Case 3: 2500050000

题解:数组模拟双链表。虽然是模拟,但是操作起来并不是很简单,应用双链表比较自然,困难的是中间的各种修改,我的第一份代码用的是学C语言的时候类似指针的操作,什么pre的next是x的next,next的pre是什么什么之类的,这种操作比较容易错的就是顺序问题,一旦顺序搞错,信息就会丢失,然后就不知道连到哪了,紫书上的方法十分优秀,提前先记录下来前驱、后继,这样不会丢失信息,顺序什么的就不用考虑了,然后把连边的操作封装到函数里,这样更是简化了思考,或者说是缩短了思维长度,经过这两个操作,原来十分费劲的修改关系就变得几乎是无脑操作了,这么好的方法一定要学会。

代码完全是按照紫书写的......

 #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
typedef long long LL; const int maxn = +;
int Next[maxn],Pre[maxn];
int cnt = ; void Link(int p,int n){
Next[p] = n,Pre[n] = p;
} int main()
{
//freopen("input.txt","r",stdin);
int n,m;
while(~scanf("%d%d",&n,&m)){
for(int i = ;i <= n;i++){
Next[i] = (i+)%(n+);
Pre[i] = i-;
}
Next[] = ,Pre[] = n;
int x,y,ope,inv = ;
for(int i = ;i <= m;i++){
scanf("%d",&ope);
if(ope == ) inv = !inv;
else{
scanf("%d%d",&x,&y);
if(inv && (ope== || ope==)) ope = -ope;
if(ope== && Pre[y]==x) continue;
if(ope== && Pre[x]==y) continue;
if(ope== && Next[y]==x) swap(x,y);
int nx = Next[x],px = Pre[x];
int ny = Next[y],py = Pre[y];
if(ope == ){
Link(px,nx);Link(py,x);Link(x,y);
}
if(ope == ){
Link(px,nx);Link(y,x);Link(x,ny);
}
if(ope == ){
if(Next[x]==y){
Link(px,y);Link(y,x);Link(x,ny);
}
else{
Link(px,y);Link(y,nx);
Link(py,x);Link(x,ny);
}
}
}
}
LL ans = ;
int t = Next[];
for(int i = ;i <= n;i++){
if(i% == ) ans += t;
t = Next[t];
}
if(inv && n%==) ans = 1LL*n*(n+)/-ans;
printf("Case %d: %lld\n",cnt++,ans);
}
return ;
}