码迷,mamicode.com
首页 > 其他好文 > 详细

UVa 12657 Boxes in a Line 双向链表

时间:2015-07-13 21:56:13      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

题目大意:
四个操作
1 X Y 把X移到Y的左边
2 X Y  把X移到Y的右边
3 X Y 交换
4 翻转

用双向链表
前两个没什么好讲的,
第三个操作要注意相邻元素之间的交换
最后一个可以用标记,然后最后计算的时候判断头尾即可(翻转后1,2 操作交换)

具体代码实现如下:
  1. #include<cstdio>
  2. using namespace std;
  3. int left[100010], right[100010];
  4. int main() {
  5. int n, m, times(0);
  6. while (scanf("%d%d", &n, &m) == 2) {
  7. for (int i = 0; i != n + 3; ++i) { //初始化左右
  8. left[i] = i - 1;
  9. right[i] = i + 1;
  10. }
  11. int op, x, y, chan(0);
  12. while (m--) {
  13. scanf("%d", &op);
  14. if (op == 4) chan = !chan;
  15. else {
  16. scanf("%d%d", &x, &y);
  17. if (chan && (op == 1 || op == 2)) {
  18. if (op == 1) op = 2;
  19. else op = 1;
  20. }
  21. if (op == 1) {
  22. left[right[x]] = left[x];
  23. right[left[x]] = right[x];
  24. left[x] = left[y];
  25. right[x] = y;
  26. right[left[y]] = x;
  27. left[y] = x;
  28. }else if (op == 2) {
  29. left[right[x]] = left[x];
  30. right[left[x]] = right[x];
  31. right[x] = right[y];
  32. left[x] = y;
  33. left[right[y]] = x;
  34. right[y] = x;
  35. }else {
  36. int lx = left[x], ly = left[y],
  37. rx = right[x], ry = right[y];
  38. if (rx == y) {
  39. left[y] = lx;
  40. right[x] = ry;
  41. right[y] = left[ry] = x;
  42. left[x] = right[lx] = y;
  43. } else if (lx == y) {
  44. left[x] = ly;
  45. right[y] = rx;
  46. right[x] = left[rx] = y;
  47. left[y] = right[ly] = x;
  48. } else {
  49. right[lx] = left[rx] = y;
  50. right[ly] = left[ry] = x;
  51. left[x] = ly;
  52. right[x] = ry;
  53. left[y] = lx;
  54. right[y] = rx;
  55. }
  56. }
  57. }
  58. }
  59. long long sum(0);
  60. int b(0);
  61. if (chan) {
  62. b = n + 1;
  63. for (int i = 1; i != n + 1; ++i) {
  64. b = left[b];
  65. if (i % 2) sum += b;
  66. // printf("%d ", b); //*
  67. }
  68. } else {
  69. for (int i = 1; i != n + 1; ++i) {
  70. b = right[b];
  71. if (i % 2) sum += b;
  72. // printf("%d ", b); //*
  73. }
  74. }
  75. printf("Case %d: %lld\n", ++times, sum);
  76. }
  77. return 0;
  78. }








UVa 12657 Boxes in a Line 双向链表

标签:

原文地址:http://www.cnblogs.com/liangyongrui/p/4643875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!