您的位置:首页 > 其它

NYOJ 511 - 移动小球 链表版

2014-03-22 19:14 232 查看
传送门NYOJ 511 - 移动小球 链表版

╮(╯▽╰)╭本来昨天要干的,可是昨天莫名的烦躁,于是就听了一个晚上的歌╮(╯▽╰)╭

刚开始写时没想到用结构体数组,..于是就各种情况各种头指针...

后来参考了一下别人的才发现可以用结构体数组来做...

这也是第一次学习双向链表,这题做完后感觉我已经差不多可以掌握了...╮(╯▽╰)╭

详情见代码 I

--------------------------------------------14. 5. 6补充.----------------------------------------------------

一个半月后重新看这题, 发现可以用STL实现, 代码将会更加简洁... 晚上回来再搞.

用STL的优点: 代码简单, 不容易出错

缺点: 由于list中查找元素的时间复杂度是O(n), 比不上用结构体数组的O(1), 所以所用时间会大大增加. 大家自己取舍.

详情见代码 II

-------------------------------------------------------------------------------------------------------------

#include <stdio.h>
struct ball
{
int num;
struct ball *left, *right;
}ball[11000];
void Initial(int n);
void Leftmove(int x, int y);
void Rightmove(int x, int y);
int main()
{
//freopen("input.txt","r",stdin);
int T;
scanf("%d",&T);
while (T--)
{
int n, m;
char c;
scanf("%d%d", &n, &m);
Initial(n);
while (m--)
{
char c;
int x, y;
getchar();
scanf("%c%d%d",&c, &x, &y);
if (c == 'A')
Leftmove(x, y);
else if (c == 'B')
Rightmove(x, y);
else
if (x == 1)
printf("%d\n",ball[y].right->num);
else
printf("%d\n",ball[y].left->num);
}
}
return 0;
}
void Initial(int n)
{
for (int i = 1; i <= n; i++)
{
ball[i].num = i;
ball[i].left = &ball[i - 1];
ball[i].right = &ball[i + 1];
}
ball[1].left = &ball
;
ball
.right = &ball[1];
}
void Leftmove(int x, int y)
{
ball[x].left->right = ball[x].right;
ball[x].right->left = ball[x].left;
ball[x].right = &ball[y];
ball[x].left = ball[y].left;
ball[x].left->right = &ball[x];
ball[y].left = &ball[x];
}
void Rightmove(int x, int y)
{
ball[x].left->right = ball[x].right;
ball[x].right->left = ball[x].left;
ball[y].right->left = &ball[x];
ball[x].right = ball[y].right;
ball[x].left = &ball[y];
ball[y].right = &ball[x];
}

代码 II

#include <bits/stdc++.h>
using namespace std;

int main()
{
//freopen("input.txt", "r", stdin);
list<int> ball;
list<int>::iterator itNow, itTarget;
int T, n, i, num, now, target;
char ch;
scanf("%d", &T);
while (T--)
{
ball.clear();
scanf("%d%d%*c", &num, &n);
for (i = 1; i <= num; i++)
ball.push_back(i);
while (n--)
{
ch = getchar();
scanf("%d%d%*c", &now, &target);
itNow = find(ball.begin(), ball.end(), now);
itTarget = find(ball.begin(), ball.end(), target);
if (ch == 'A')
{
ball.insert(itTarget, now);
ball.erase(itNow);
}
else if (ch == 'B')
{
ball.insert(++itTarget, now);
ball.erase(itNow);
}
else		//1询问右边的, 0左边.
{
if (now == 1 && itTarget == --ball.end())
printf("%d\n", *ball.begin());
else if (now == 0 && itTarget == ball.begin())
printf("%d\n", *(--ball.end()));
else if (now == 1)
printf("%d\n", *(++itTarget));
else if (now == 0)
printf("%d\n", *(--itTarget));
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NYOJ ACM