Блог пользователя antivenom

Автор antivenom, 9 лет назад, По-английски

Hello,After seeing this question the first thing came to my mind was Dynamic programming.I tried constructing a solution but could not make it,maybe because i don't have that much of experience.

  #include <bits/stdc++.h>
  using namespace std;
  int main() 
  {
      int n,m,a,b; 
      cin>>n>>m>>a>>b;
      int final=0,dp[n+1];
      dp[0]=0;
      for(int i=1;i<=n;i++)
	 dp[i]=min(dp[i-1]+a,dp[i-m]+b);
      cout<<dp[n];
      return 0;
 }

P.S:I know it can be solved without using Dp,but i request you to give Dp approach if it is possible.

  • Проголосовать: нравится
  • -3
  • Проголосовать: не нравится

»
9 лет назад, # |
Rev. 5   Проголосовать: нравится 0 Проголосовать: не нравится

for i =  1 ... m - 1 dp[i - m] is undefined.

you may have WA in cases when prefered buy the special ticket for more than n rides.

correct solution

»
9 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

if(i>=m) dp[i] = min(dp[i-1]+a,dp[i-m]+b); else dp[i]=min(dp[i-1]+a,b);

  • »
    »
    9 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    After putting your condition it fails on testcase 8.Before that it used to fail on 3.So some improvement is there.

    • »
      »
      »
      9 лет назад, # ^ |
      Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

      My solution Got accepted lol

      Link Can you post a link of your solution ?

      • »
        »
        »
        »
        9 лет назад, # ^ |
          Проголосовать: нравится 0 Проголосовать: не нравится

        Bingo!!!Correct answer!!!...Please explain me else part of the recursion :)

        • »
          »
          »
          »
          »
          9 лет назад, # ^ |
            Проголосовать: нравится 0 Проголосовать: не нравится
          With a ticket for 'm' rides, you can travel m times or less. 
          

          Lets take this example : 7 5 5 1 Here the minimum cost for travelling 1...5 times is 1 . so DP[1...5] should have a value of 2.