题目链接
最开始没注意到n的数据量,傻乎乎的建树…
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<string>
typedef long long ll;
const int maxn = 1e6 + 5;
const int INF = 0x3f3f3f3f;
using namespace std;
int tree[maxn], n, Node[maxn];
void build(int dis, int node) {
if (dis == 0) return;
if (node == 1) tree[node] = n / 2;
else if (!(node & 1)) tree[node] = tree[node >> 1] - dis;
else if (node & 1) tree[node] = tree[(node - 1) >> 1] + dis;
Node[tree[node]] = node;
build(dis >> 1, node << 1);
build(dis >> 1, node << 1 | 1);
}
int main() {
int T;
scanf("%d %d", &n, &T); n++;
build(n / 2, 1);
while (T--) {
int exp;
scanf("%d", &exp);
exp = Node[exp];
char oper[maxn];
memset(oper, 0, sizeof(oper));
scanf("%s", oper);
for (int i = 0; i < strlen(oper); i++) {
if (oper[i] == 'U' && exp != 1)
if (exp & 1) exp = exp >> 1 - 1;
else exp = exp >> 1;
else if (oper[i] == 'L' && exp < n / 2) exp = exp << 1;
else if (oper[i] == 'R' && exp < n / 2) exp = exp << 1 | 1;
}
printf("%d\n", tree[exp]);
}
}
AC代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<string>
typedef long long ll;
const int maxn = 1e6 + 5;
const int INF = 0x3f3f3f3f;
using namespace std;
char s[100000];
int main() {
ll n, T, node;
scanf("%lld %lld", &n, &T);
while (T--) {
scanf("%lld %s", &node, s);
for (int i = 0; i < strlen(s); i++) {
ll dis = node & (-node); //二进制最末位对应数字为其与父节点的差值
if (s[i] == 'L') node -= (dis >> 1);
if (s[i] == 'R') node += (dis >> 1);
if (s[i] == 'U') {
if (((n + 1) >> 1) == node) continue;
if ((dis << 1) == ((node - dis) & (dis - node))) node -= dis; //所处节点为右节点
else node += dis; //所处节点为左节点
}
}
printf("%lld\n", node);
}
}