题目:
一行盒子
Crawling failed
Submit Status Practice CSU 1329
Description
你有一行盒子,从左到右依次编号为1, 2, 3,…, n。你可以执行四种指令:
1 X Y表示把盒子X移动到盒子Y左边(如果X已经在Y的左边则忽略此指令)。
2 X Y表示把盒子X移动到盒子Y右边(如果X已经在Y的右边则忽略此指令)。
3 X Y表示交换盒子X和Y的位置。
4 表示反转整条链。
指令保证合法,即X不等于Y。例如,当n=6时在初始状态下执行1 1 4后,盒子序列为2 3 1 4 5 6。接下来执行2 3 5,盒子序列变成2 1 4 5 3 6。再执行3 1 6,得到2 6 4 5 3 1。最终执行4,得到1 3 5 4 6 2。
Input
输入包含不超过10组数据,每组数据第一行为盒子个数n和指令条数m(1<=n,m<=100,000),以下m行每行包含一条指令。
Output
每组数据输出一行,即所有奇数位置的盒子编号之和。位置从左到右编号为1~n。
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
Sample Output
Case 1: 12
Case 2: 9
Case 3: 2500050000
题目大意:
中文题目
题目思路:
1、因为题目给的四种方式没有删除或增加,可以用简单的链表思想
2、每个数定义两个指针,分别指向左边和右边的数.开头为0,结尾为n+1
3、当要调位置的时候改变指针即可
注意:
4、操作的时候可能有 (x和y为操作数,其他为相邻的数): X a b y x a y x y y a b y y a x y x 6种情况
5、在翻转的状态时候 注意原本调到后面的要放到前面...前面的放到后面
6、翻转两次就没有翻转状态
7、注意先取出来 ,再放进去 防止 x 和 y 相邻的情况错误
程序:
#include<iostream>
#include<cstdio>
#include<map>
#include<math.h>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m;
struct node
{
int l,r;
} a[100100];
int line(int ,int );
int solve(int);
int ini();
int main()
{
int cas=1;
while(~scanf("%d %d",&n,&m))
{
printf("Case %d: ",cas++);
ini();
int f=0;
while(m--)
{
int x,y,z,mi;
scanf("%d",&mi);
if(mi==4)
{
f=!f;
continue;
}
scanf("%d %d",&x,&y);
if(mi==2&&f==0||mi==1&&f==1)//注意翻转状态
{
line(a[x].l,a[x].r);//先取出来
z=a[y].r;
line(y,x);//再链接
line(x,z);
}
else if(mi==1&&f==0||mi==2&&f==1)
{
line(a[x].l,a[x].r);
z=a[y].l;
line(z,x);
line(x,y);
}
else if(mi==3)
{
int b,c,d;
z=a[x].l;
b=a[x].r;
c=a[y].l;
d=a[y].r;
if(a[x].r==y)//注意x 和 y 的位置关系
{
line(z,y);
line(x,d);
line(y,x);
}
else if(a[x].l==y)
{
line(c,x);
line(y,b);
line(x,y);
}
else
{
line(z,y);
line(y,b);
line(c,x);
line(x,d);
}
}
}
solve(f);
}
return 0;
}
int ini()
{
for(int i=0; i<=n+1; i++)
a[i].l=i-1,a[i].r=i+1;
}
int solve(int f)
{
int p=0;
long long int ans=0;
for(int i=1; p<=n; i=!i)//到n+1截止
{
if(i==f)
{
ans+=p;
}
p=a[p].r;//一直向右
}
cout<<ans<<endl;
}
int line(int x,int y)//链接
{
a[x].r=y;
a[y].l=x;
}