What is the difference between these two solutions for Silver Following Directions?
The first solution is my code after reading the analysis.
The second solution is Danny Mittal’s code translated into C++.
I understand the problem conceptually, I just can’t find the bug in solution 1.
Solution 1:
#include<bits/stdc++.h>
using namespace std;
// grid of signposts, 'R'=1, 'D'=0;
bool grid[1502][1502];
// how many cows pass through i,j
int A[1502][1502];
// cost of vats
int cost[1502][1502];
int main(){
int n; cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
char c; cin>>c;
grid[i][j]=(c=='R');
}
cin>>cost[i][n+1];
}
for(int i=1;i<=n;i++) cin>>cost[n+1][i];
// calculate starting values of A and answer
int ans=0;
for(int i=1;i<=n+1;i++){
for(int j=1;j<=n+1;j++){
if(i==n+1||j==n+1) ans+=A[i][j]*cost[i][j];
else {
A[i][j]++;
if(grid[i][j]) A[i][j+1]+=A[i][j];
else A[i+1][j]+=A[i][j];
}
}
}
// print original value of answer
cout<<ans<<"\n";
int q; cin>>q;
for(int k=0;k<q;k++){
ans=0;
int i,j;
cin>>i>>j;
// recalculate old path
int r=i,c=j;
while(r!=n+1&&c!=n+1){
r+=!grid[r][c];
c+=grid[r][c];
A[r][c]-=A[i][j];
}
// flip the sign
grid[i][j]=!grid[i][j];
// calculate new path
r=i,c=j;
while(r!=n+1&&c!=n+1){
r+=!grid[r][c];
c+=grid[r][c];
A[r][c]+=A[i][j];
}
// calculate new answer
for(int l=1;l<=n;l++){
ans+=A[n+1][l]*cost[n+1][l];
ans+=A[l][n+1]*cost[l][n+1];
}
cout<<ans<<"\n";
}
}
Solution 2:
#include<bits/stdc++.h>
using namespace std;
string dirs[1502];
int weights[1502][1502];
int main(){
int n; cin>>n;
for(int y=0;y<n;y++){
string c; cin>>c;
dirs[y]=c;
cin>>weights[y][n];
}
for(int x=0;x<n;x++){
cin>>weights[n][x];
}
int amtReach[n+1][n+1];
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
amtReach[i][j]=0;
}
}
int answer=0;
for (int y = 0; y <= n; y++) {
for (int x = 0; x <= n; x++) {
if (y == n || x == n) {
answer += amtReach[y][x] * weights[y][x];
} else {
amtReach[y][x]++;
if (dirs[y][x] == 'R') {
amtReach[y][x + 1] += amtReach[y][x];
} else {
amtReach[y + 1][x] += amtReach[y][x];
}
}
}
}
cout<<answer<<"\n";
int k; cin>>k;
for (int q = k; q > 0; q--) {
int y,x;
cin>>y>>x;
y--,x--;
int v = y;
int u = x;
while (v != n && u != n) {
if (dirs[v][u] == 'R') {
u++;
} else {
v++;
}
amtReach[v][u] -= amtReach[y][x];
}
answer -= amtReach[y][x] * weights[v][u];
if (dirs[y][x] == 'R') {
dirs[y][x] = 'D';
} else {
dirs[y][x] = 'R';
}
v = y;
u = x;
while (v != n && u != n) {
if (dirs[v][u] == 'R') {
u++;
} else {
v++;
}
amtReach[v][u] += amtReach[y][x];
}
answer += amtReach[y][x] * weights[v][u];
cout<<answer<<"\n";
}
}