移动撤销

https://ac.nowcoder.com/acm/contest/8997/B

方法一:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int f[4][2]={{0,1},{-1,0},{0,-1},{1,0}};
 4 int n;
 5 string s;
 6 struct node{
 7     int x, y;
 8 }t;
 9 stack<node>stk;
10 int main()
11 {
12     cin>>n;
13     cin>>s;
14     t.x=0;
15     t.y=0;
16     stk.push(t);
17     for(int i=0; i<n; i++){
18         //cout<<stk.top().x<<" "<<stk.top().y<<endl;
19         if(s[i]=='W'){
20             t.x=stk.top().x+f[0][0];
21             t.y=stk.top().y+f[0][1];
22             stk.push(t);
23         }
24         if(s[i]=='A'){
25             t.x=stk.top().x+f[1][0];
26             t.y=stk.top().y+f[1][1];
27             stk.push(t);
28         }
29         if(s[i]=='S'){
30             t.x=stk.top().x+f[2][0];
31             t.y=stk.top().y+f[2][1];
32             stk.push(t);
33         }
34         if(s[i]=='D'){
35             t.x=stk.top().x+f[3][0];
36             t.y=stk.top().y+f[3][1];
37             stk.push(t);
38         }
39         if(s[i]=='Z'){
40             if(stk.size()!=1){
41                 stk.pop();
42             }
43         }
44     }
45     cout<<stk.top().x<<" "<<stk.top().y;
46     return 0;
47  }

方法二:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int main() {
 5     int n;
 6     cin >> n;
 7     string a;
 8     cin >> a;
 9     stack<char> s;
10     int x = 0, y = 0;
11     for(int i = 0; i < n; i++) {
12         if(a[i] != 'Z') s.push(a[i]);
13         else if(!s.empty()) s.pop();
14     }
15 
16     while(!s.empty()) {
17         char c = s.top();
18         s.pop();
19         if(c == 'W') y++;
20         else if(c == 'A') x--;
21         else if(c == 'S') y--;
22         else if(c == 'D') x++;
23     }
24     cout << x << " " << y << endl;
25 }
原文地址:https://www.cnblogs.com/tflsnoi/p/14071406.html