题目大意:
给出地雷的坐标和一组行进方向指令,问能否通过改变指令的顺序避开地雷,若能则输出序列。
思路:
如果雷埋在起点或终点,那我们无法躲避。
如果埋在其他的点上,从直观上来说我们有挺多的躲避线路,毕竟雷只有一个,而我们可以在无限大平面上任选四个方向进行移动。考虑模拟四个方向的不同排列check是否经过地雷,如果单纯的进行模拟或着dfs/bfs,时间肯定不能接受,那么我们考虑使得相同的方向连续排在一起,因为正如前面所说,碰到雷的概率其实并不高,而我们可以由四个方向{UDLR}得到24种排列,枚举排列再进行暴力模拟,期望得到一种避开雷的排列。
题解说可以证明存在一种答案,使得相同的方向是连续排在一起的。蒟蒻并不是很会证。
Code:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PI;
const double eps = 1e-6;
const int N = 200010;
const int INF = 0x3f3f3f3f;
const int mod = 1000000007; //998244353
LL powmod(LL a, LL b) { LL res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a % mod; a = a * a % mod; }return res; }
const int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int a[4] = {0, 1, 2, 3}; //上下左右
int cnt[4] = {0}; //上下左右
unordered_map<int, char> mp;
int mx, my;
bool check() { //模拟走
int x = 0, y = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < cnt[a[i]]; j++) {
x += dir[a[i]][0];
y += dir[a[i]][1];
if (x == mx && y == my) return false;
}
}
return true;
}
void init() {
for (int i = 0; i < 4; i++) cnt[i] = 0, a[i] = i;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
mp[0] = 'U', mp[1] = 'D', mp[2] = 'L', mp[3] = 'R';
int T; cin >> T;
while (T--) {
init();
cin >> mx >> my;
string s; cin >> s;
int x = 0, y = 0; //终点坐标
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'U')
cnt[0]++, y++;
if (s[i] == 'D')
cnt[1]++, y--;
if (s[i] == 'L')
cnt[2]++, x--;
if (s[i] == 'R')
cnt[3]++, x++;
}
if (mx == 0 && my == 0 || mx == x && my == y) {
cout << "Impossible" << endl;
continue;
}
bool ok = false;
do {
if (check()) {
ok = true;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < cnt[a[i]]; j++) {
cout << mp[a[i]];
}
}
cout << endl;
break;
}
} while (next_permutation(a, a + 4));
if (!ok)
cout << "Impossible" << endl;
}
return 0;
}