407B - Long Path - CodeForces Solution


dp implementation *1600

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#include <algorithm>


#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
 
typedef long long int ll;
using namespace std;
 
 
ll mydiv(ll a, ll b){
    if( a % b == 0)
        return a / b;
    else
        return (a / b) + 1;
}
 
long long gcd(long long int a, long long int b)
{
  if (b == 0)
    return a;
  return gcd(b, a % b);
}
 
// Function to return LCM of two numbers
long long lcm(ll a, ll b)
{
    return (a / gcd(a, b)) * b;
}

void solve(){
    
    ll n, m = 1000000007;
    cin>>n;
    
    vector <ll> v(n + 1), dp(n + 1);
    
    for(ll i = 1; i <= n; i++)
        cin>>v[i];
    
    dp[0] = 0;
    
    for(ll i = 1; i <= n; i++){
        if(v[i] == i)
            dp[i] = (dp[i - 1] + 2) % m;
        else{
            if(dp[i - 1] <= dp[v[i] - 1])
                dp[i] = ((dp[i - 1] + 2) % m + (m + dp[i - 1] - dp[v[i] - 1]) % m) % m;
            else
                dp[i] = ((dp[i - 1] + 2) % m + (dp[i - 1] - dp[v[i] - 1]) % m) % m;
        }
    }
    cout<<dp[n];
}

int main(){
    
    ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
    solve();
	
	return 0;
}


Comments

Submit
0 Comments
More Questions

1283B - Candies Division
1451B - Non-Substring Subsequence
1408B - Arrays Sum
1430A - Number of Apartments
1475A - Odd Divisor
1454B - Unique Bid Auction
978C - Letters
501B - Misha and Changing Handles
1496A - Split it
1666L - Labyrinth
1294B - Collecting Packages
1642B - Power Walking
1424M - Ancient Language
600C - Make Palindrome
1669D - Colorful Stamp
1669B - Triple
1669A - Division
1669H - Maximal AND
1669E - 2-Letter Strings
483A - Counterexample
3C - Tic-tac-toe
1669F - Eating Candies
1323B - Count Subrectangles
991C - Candies
1463A - Dungeon
1671D - Insert a Progression
1671A - String Building
1671B - Consecutive Points Segment
1671C - Dolce Vita
1669G - Fall Down