算法提高 盾神与条状项链 双向链表

转自 http://blog.csdn.net/flyawayl/article/details/60588012


     思路:用双向链表,next[x] = y表示颜色为x的珠子的下一个珠子的颜色是y,pre[x] = y表示表示颜色为x的珠子的上一个珠子的颜色是y。时间复杂度是O(n + m)

[cpp]  view plain  copy
  1. #include <cstdio>  
  2. #include <cmath>  
  3. #include <algorithm>  
  4. #include <cstring>  
  5. #include <utility>  
  6. #include <string>  
  7. #include <iostream>  
  8. #include <map>  
  9. #include <set>  
  10. #include <vector>  
  11. #include <queue>  
  12. #include <stack>  
  13. using namespace std;  
  14. #pragma comment(linker, "/STACK:1024000000,1024000000")   
  15. #define eps 1e-10  
  16. #define inf 0x3f3f3f3f  
  17. #define PI pair<int, int>   
  18. typedef long long LL;  
  19. const int maxn = 1e5 + 5;  
  20. int next[maxn], pre[maxn];  
  21. int n, m, head, len;  
  22. //双向链表   
  23.   
  24. void Insert(int key, int pos1, int pos2) {  
  25.     ++len;  
  26.     next[key] = pos2;  
  27.     next[pos1] = key;  
  28.     pre[key] = pos1;  
  29.     pre[pos2] = key;  
  30. }  
  31. void init(int n) {  
  32.     head = 0; next[head] = 0; pre[head] = 0;  
  33.     int x, prev = 0;  
  34.     for(int i = 0; i < n; ++i) {  
  35.         scanf("%d", &x);  
  36.         Insert(x, prev, next[prev]);  
  37.         prev = x;  
  38.     }  
  39. }  
  40. void Delete(int key, int pos1, int pos2) {  
  41.     --len;  
  42.     next[pos1] = pos2;  
  43.     pre[pos2] = pos1;  
  44. }  
  45. void print() {  
  46.     printf("%d\n", len);   
  47.     int nex = next[head];  
  48.     while(nex) {  
  49.         printf("%d ", nex);  
  50.         nex = next[nex];  
  51.     }  
  52.     printf("\n");  
  53. }  
  54. int main() {  
  55.     while(scanf("%d%d", &n, &m) == 2) {  
  56.         len = 0;  
  57.         init(n);  
  58.         char op[5];  
  59.         int x, y;  
  60.         for(int i = 0; i < m; ++i) {  
  61.             scanf("%s", op);  
  62.             if(op[0] == 'A') {  
  63.                 scanf("%d%d", &x, &y);  
  64.                 Insert(y, pre[x], x);  
  65.             }  
  66.             else {  
  67.                 scanf("%d", &x);  
  68.                 Delete(x, pre[x], next[x]);  
  69.             }  
  70.         }  
  71.         print();  
  72.     }  
  73.     return 0;  
  74. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值