forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path(SPOJ)MISERMAN.cpp
81 lines (67 loc) · 1.13 KB
/
(SPOJ)MISERMAN.cpp
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
//Author: rishab_1128
#include<bits/stdc++.h>
using namespace std;
#define Min(x,y,z) min(x,min(y,z))
void solve()
{
int n,m;
cin>>n>>m;
int**fares=new int*[n];
for(int i=0; i<n; i++)
{
fares[i]=new int[m];
for(int j=0; j<m; j++)
cin>>fares[i][j];
}
int**dp=new int*[n];
for(int i=0; i<n; i++)
{
dp[i]=new int[m];
}
//Initialising the 1st row of the DP
for(int j=0; j<m; j++)
{
dp[0][j]=fares[0][j];
}
for(int i=1; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(j==0)
dp[i][j]=min(dp[i-1][j],dp[i-1][j+1])+fares[i][j];
else if(j==m-1)
dp[i][j]=min(dp[i-1][j],dp[i-1][j-1])+fares[i][j];
else
dp[i][j]=Min(dp[i-1][j],dp[i-1][j+1],dp[i-1][j-1])+fares[i][j];
}
}
int ans=INT_MAX;
for(int j=0; j<m; j++)
{
ans=min(ans,dp[n-1][j]);
}
//Deleting the fares and DP array
for(int i=0; i<n; i++)
{
delete[]fares[i];
delete[]dp[i];
}
delete[]fares;
delete[]dp;
cout<<ans<<endl;
}
int main()
{
std::ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
//cin>>t;
while(t--)
{
solve();
}
return 0;
}