combinatorics constructive algorithms greedy math *1900

Please click on ads to support us..

Python Code:

def solve():
    mod = 1000000007
    n, k = map(int, input().strip().split())

    res = pow(2, n, mod)

    if k >= n:
        print(res)
    elif k + 1 == n:
        print(res - 1)
    else:
        ans = 1
        temp1 = 1
        temp2 = 1
        for i in range(1, n - k):
            temp1 *= (n - i + 1)
            temp1 %= mod
            temp2 *= i
            temp2 %= mod
            ans += temp1 * pow(temp2, mod - 2, mod) % mod
        print((res - ans + mod) % mod)


if __name__ == '__main__':
    solve()

C++ Code:

#include <bits/stdc++.h>
#define ll long long
#define F first
#define S second
#define pb push_back
#define B break
#define C continue
#define mid ((l+r)/2)
#define left (2*idx)
#define right (2*idx+1)

using namespace std;

const ll Mod=1e9+7 , N = 500500 , inf=1e18;
ll n , m , k , q , x , y , z , a[N], fact[N], inv[N] , ans=0 , sum=0 , mn=inf , mx=0 ;

ll poww(ll a,ll b,ll Mod){
    ll res=1;if(b<0)b=(b%(Mod-1)+Mod-1)%(Mod-1);
    for(;b;b>>=1,a=1ll*a*a%Mod)
        if(b&1)res=1ll*res*a%Mod;
    return res;
}

ll Cnk(ll n,ll k){
    if(k>n)return 0;
    return (((fact[n]*inv[k])%Mod) * inv[n-k])%Mod;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    fact[0]=1;
    for(ll i=1 ; i<N ; i++)     fact[i] = (fact[i-1]*i)%Mod;

    inv[N-1] = poww(fact[N-1],-1,Mod);
    for(ll i=N-2 ; i>=0 ; i--)  inv[i] = (inv[i+1]*(i+1))%Mod;

    int t=1;
    //cin >> t ;
    while(t--){
        bool ok=1;
        cin >> n >> k ;
        ans=0;
        for(int i=0 ; i<=k && i<=n ; i++){
            ans += Cnk(n,i);
            ans %= Mod;
        }
        cout << ans << endl;
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts
Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship