题解 | #坐标移动#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
主要思路:按分号作为分隔点,获取所有合法的坐标移动序列,再按坐标顺序模拟一遍即可。
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
using namespace std;
const int N = 6000;
string a[N];
int main()
{
string s;
cin >> s;
//cnt 记录合法移动序列的个数,last 记录上一个分号的下一个位置
int cnt = 0, last = 0;
for (int i = 0; i < s.size(); i ++)
{
if (s[i] != ';') continue;
string tmp = s.substr(last, i - last);
if (tmp[0] == 'W' || tmp[0] == 'A' || tmp[0] == 'S' || tmp[0] == 'D')
{
bool f = true;
for (int i = 1; i < tmp.size(); i ++)
if (!isdigit(tmp[i])) f = false;
if (f) a[++ cnt] = tmp;
}
last = i + 1;
}
int x = 0, y = 0;
for (int i = 1; i <= cnt; i ++)
{
char d = a[i][0];
int num = stoi(a[i].substr(1, a[i].size() - 1));
if (d == 'W') y += num;
else if (d == 'S') y-= num;
else if (d == 'A') x -= num;
else x += num;
}
cout << x << ',' << y << endl;
return 0;
}