1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| const int maxn = 70 + 5; const int inf = 0x3f3f3f3f; char str[maxn];
const int UP = 0; const int LEFT = 1; const int RIGHT = 2; const int DOWN = 3;
// === init ID == map<char, int> ID; void initID() { ID['U'] = 0; ID['L'] = 1; ID['R'] = 2; ID['D'] = 3; } // == init finished ==
// == data structure const char footch[] = ".LR"; int d[maxn][4][4][3]; int act[maxn][4][4][3];
// == compute energy == // (f0 != f), return 1 int energy(int a, int ta) { if(a == ta) return 3; if(a + ta == 3) return 7; return 5; }
int energy(int a, int& ta, int b, int& tb, int f0, int f, int t) { ta = a, tb = b; if(f == 1) ta = t; else if(f == 2) tb = t;
if(ta == tb) return -1; if(ta == RIGHT && tb == LEFT) return -1; if(ta == RIGHT && tb != b) return -1; if(tb == LEFT && ta != a) return -1;
int ans = 0; if(f == 0) ans = 0; else if(f != f0) ans = 1; else { if(f == 1) ans = energy(a, ta); else if(f == 2) ans = energy(b, tb); } return ans; }
void update(int i, int a, int b, int f0, int f, int t) { int ta, tb; int e = energy(a, ta, b, tb, f0, f, t); if(e < 0) return;
int& ans = d[i][a][b][f0]; int cost = d[i+1][ta][tb][f] + e;
if(chmin(ans, cost)) { act[i][a][b][f0] = f * 4 + t; }
} // == compute finished ==
void initdp() { memset(d, 0, sizeof(d)); }
void dp(int n) { for(int i = n - 1; i >= 0; i--) { _for(a, 0, 4) _for(b, 0, 4) if(a != b) { _for(f0, 0, 3) { d[i][a][b][f0] = inf;
if(str[i] == '.') { update(i, a, b, f0, 0, 0); _for(t, 0, 4) { update(i, a, b, f0, 1, t); update(i, a, b, f0, 2, t); } } else { update(i, a, b, f0, 1, ID[str[i]]); update(i, a, b, f0, 2, ID[str[i]]); } } } } }
void printAns(const int n, int i, int a, int b, int f0) { if(i == n) return;
int f = act[i][a][b][f0] / 4; int t = act[i][a][b][f0] % 4; printf("%c", footch[f]);
int na = a, nb = b, nf = f; if(f == 1) na = t; else if(f == 2) nb = t;
printAns(n, i + 1, na, nb, nf); }
void init() { memset(d, 0, sizeof(d)); memset(act, 0, sizeof(act)); }
int main() { freopen("input.txt", "r", stdin);
initID(); while (scanf("%s", str) == 1) { if(str[0] == '#') break;
init(); // then dp
initdp(); int n = strlen(str); dp(n); printAns(n, 0, LEFT, RIGHT, 0); printf("\n"); } }
|