0% found this document useful (0 votes)
11 views2 pages

Submission 191898544497392

The document describes an algorithm to solve a problem involving matching cells in two strings while minimizing a cost function. It includes code to implement dynamic programming to solve the problem, iterating through the strings and building up a cost table to find the optimal solution.

Uploaded by

Samin Afnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Submission 191898544497392

The document describes an algorithm to solve a problem involving matching cells in two strings while minimizing a cost function. It includes code to implement dynamic programming to solve the problem, iterating through the strings and building up a cost table to find the optimal solution.

Uploaded by

Samin Afnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <bits/stdc++.

h>
using namespace std;
inline int transition(int x, int px, int py, char c) {
if (c == 'X') {
return 0;
}
if (x == 2 || px == 1) {
return 2;
}
if (x == 1 || (px == 0 && py == 0)) {
return 1;
}
return 0;
}
const int inf = (int)1e9;
const int N = 123456;
int f[N][3][3];
char s[2][N];
int main() {
freopen("in", "r", stdin);
freopen("out", "w", stdout);
int tt;
scanf("%d", &tt);
for (int qq = 1; qq <= tt; qq++) {
printf("Case #%d: ", qq);
int n;
scanf("%d", &n);
scanf("%s", s[0]);
scanf("%s", s[1]);
// 0 -- all set
// 1 -- unmatched cells to the left
// 2 -- a guard matching cells to the right
for (int i = 0; i <= n; i++) {
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
f[i][x][y] = inf;
}
}
}
f[0][0][0] = 0;
for (int i = 0; i < n; i++) {
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
if (f[i][x][y] >= inf) {
continue;
}
if ((x == 1 && s[0][i] == 'X') || (y == 1 && s[1][i] == 'X')) {
// can't match unmatched cells to the left anymore
continue;
}
for (int px = 0; px < 2; px++) {
for (int py = 0; py < 2; py++) {
if ((px == 1 && s[0][i] == 'X') || (py == 1 && s[1][i] == 'X')) {
// can't place a guard into a building
continue;

}
int
int
int
f[i

ft = f[i][x][y] + px +
nx = transition(x, px,
ny = transition(y, py,
+ 1][nx][ny] = min(f[i

}
}
}
}
}
int ans = inf;
for (int x = 0; x < 3; x += 2) {
for (int y = 0; y < 3; y += 2) {
ans = min(ans, f[n][x][y]);
}
}
printf("%d\n", ans);
}
return 0;
}

py;
py, s[0][i]);
px, s[1][i]);
+ 1][nx][ny], ft);

You might also like