[关闭]
@sensitive-cs 2016-11-22T15:49:08.000000Z 字数 800 阅读 673

2016.11.22


铁轨问题:
a是原序列的标记指针,b是标记目标序列的指针,这点理解了就好了。
另,第一个判断当前的目标序列是否与原序列的现在相等,第二个是当中转站中不为0时,让中转站的元素与目标相比,第三个是当两个条件都不满足时,则让栈中的元素增加。
代码

  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. int target[20] = {0};
  5. int stack[20] = {0};
  6. int a = 1,b = 1;
  7. int i;
  8. int n;
  9. scanf("%d",&n);
  10. for (i = 1;i <= n;i++)
  11. scanf("%d",&target[i]);
  12. int top = 0;
  13. int ok = 1;
  14. while (b <= n)
  15. {
  16. if (target[a] == stack[b]) {a++;b++;}
  17. else if (top && (stack[top] == target[b])) {top--;b++;}
  18. else if (a <= n) stack[top] = a++;
  19. else ok = 0;
  20. }
  21. if (ok) printf("yes\n");
  22. else printf("no\n");
  23. return 0;
  24. }

c++:

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. stack<int> s;
  4. int main(void)
  5. {
  6. int b[20] = {0};
  7. int n;
  8. scanf("%d",&n);
  9. for (int i = 1;i <= n;i++)
  10. scanf("%d",&b[i]);
  11. int x = 1,y = 1;
  12. int ok = 1;
  13. while (x <= n)
  14. {
  15. if (y == b[x]) {y++;x++;}
  16. else if (!s.empty() && s.top() == b[x]) {s.pop();x++;}
  17. else if (y <= n) s.push(y++);
  18. else {ok = 0;break;}
  19. }
  20. if (ok) printf("yes\n");
  21. else printf("no\n");
  22. return 0;
  23. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注