题目
题意: 起点为(0,0),终点为(x,y),给定一组上下左右的串,可以对其任意重排序,判断是否存在一个序列使得该点不会走到(x,y),若存在,输出方案.
思路: 本来想的逆着走,但是发现不对,能被hack掉。情况非常多,分支判会很多。所以应该暴力,暴力枚举UDLR的顺序,然后模拟判断是否合法,也就4! * n.
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int n,m; int x,y;
int cnt[5];
bool flag;
string t;
int a[4];
int get(char ch)
{
if(ch=='U') return 1;
else if(ch=='D') return 2;
else if(ch=='L') return 3;
else return 4;
}
char get2(int x)
{
if(x==1) return 'U';
if(x==2) return 'D';
if(x==3) return 'L';
if(x==4) return 'R';
}
void fun(int &x,int &y,int wh)
{
if(wh==1) y++;
else if(wh==2) y--;
else if(wh==3) x--;
else x++;
if(x==n&&y==m) flag = 0;
}
void fun2(int id)
{
// int x = 0;
for(int i=0;i<cnt[id];++i)
{
t += get2(id);
// cnt[id]--;
fun(x,y,id);
}
}
void solve()
{
for(int i=1;i<=4;++i) cnt[i] = 0;
cin>>n>>m;
string s; cin>>s;
for(int i=0;i<s.size();++i)
{
int id = get(s[i]);
cnt[id]++;
}
if(n==0&&m==0)
{
cout<<"Impossible\n"; return ;
}
for(int i=0;i<4;++i) a[i] = i+1;
do
{
t.clear(); flag = 1; x = 0,y = 0;
for(int i=0;i<4;++i) fun2(a[i]);
if(flag)
{
cout<<t<<"\n"; return ;
}
}while(next_permutation(a,a+4));
cout<<"Impossible\n";
}
signed main(void)
{
// for(int i=0;i<4;++i) a[i] = i+1;
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int T; cin>>T;
while(T--)
solve();
return 0;
}