题解:AT_abc454_e [ABC454E] LRUD Moving

· · 题解

建议评绿。

思路

首先黑白染色后可以发现,每次移动就是从黑点到白点,或者从白点到黑点。因为起点和终点都是白点,所以要经过所有点,要保证黑点数比白点数少一个。也就是,n 为偶数且 x+y 为奇数时,才有可能达到要求。

下面给一种构造性证明这种情况一定能达到要求:

例如,n=6,x=3,y=4 时,可以这么构造:

代码

#include <bits/stdc++.h>
#define ll long long
#define pii pair <int, int>
#define pll pair <ll, ll>
#define fi first
#define se second
#define y1 noip200
#define stp(x) fixed << setprecision(x)

using namespace std;

const int N = 5e5 + 50, p = 1e9 + 7, inf = 1 << 29;

int n, x, y;

void init() {

}

void solve() {
    cin >> n >> x >> y;
    if (n % 2 == 1 || (x + y) % 2 == 0) {
        cout << "No\n";
        return;
    }
    cout << "Yes\n";
    int a = 1, b = 1;
    for (int i = 1; i < (y + 1) / 2; i++) {
        for (int j = 1; j < n; j++) cout << "D", a++;
        cout << "R", b++;
        for (int j = 1; j < n; j++) cout << "U", a--;
        cout << "R", b++;
    }
    bool ok = 0;
    for (int i = 1; i < n; i++) {
        if (i & 1) {
            if ((a == x && b + 1 == y) || ok) cout << "DR", ok = 1;
            else cout << "RD";
            a++, b++;
        } else {
            if ((a == x && b - 1 == y) || ok) cout << "DL", ok = 1;
            else cout << "LD";
            a++, b--;
        }
    }
    for (int i = 1; i <= n / 2 - (y + 1) / 2; i++) {
        cout << "R", b++;
        for (int j = 1; j < n; j++) cout << "U", a--;
        cout << "R", b++;
        for (int j = 1; j < n; j++) cout << "D", a++;
    }
    cout << endl;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    init();
    int t = 1;
    cin >> t;
    while (t--) solve();
    return 0;
}