
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Handshakes That Don't Cross in C++
Suppose we have an even number of people n that stand around a circle and each person shakes hands with someone else, so that there will be n / 2 handshakes total. We have to find the number of ways these handshakes could occur such that none of the handshakes cross. The answers may be very large so return the answer mod 10^9 + 7.
So, if the input is like n = 2, then the output will be 1
To solve this, we will follow these steps −
m := 10^9 + 7
Define an array dp of size (n+1)
dp[0] := 1
for initialize i := 0, when i <= n, update i := i + 2, do −
for initialize j := 0, when j <= i-2, update j := j + 2, do −
dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m)
dp[i] := dp[i] mod m
return dp[n] mod m
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; const int m = 1e9+7; typedef long long int lli; class Solution { public: int numberOfWays(int n) { vector <lli> dp(n+1); dp[0] = 1; for(int i = 0; i <= n; i+=2 ){ for(int j =0 ; j <= i-2; j+=2){ dp[i] += (dp[j]%m * dp[i-2-j]%m)%m; dp[i]%=m; } } return dp[n]%m; } }; main(){ Solution ob; cout << (ob.numberOfWays(2)); }
Input
2
Output
1
- Related Articles
- 6 Skin-Care ingredient combinations that don’t mix
- What are some signs that tell me that I don't have enough protein in my diet?
- C++ program to remove Nodes that Don't Lie in Any Path With Sum>=k
- 16 Celebrities Who Don't Drink Alcohol
- Why Don't Transformers Work on DC Supply?
- What are the best new products or inventions that most people don't know about?
- Why do the two oceans in Alaska don't mix?
- What do we don't get echo in small room?
- You said real image is inverted, then why don't we see like that in cinema halls ?
- Covalent compounds generally don't conduct electricity. Give Reason.
- Why don't non living things respond to stimulus ?
- Why don't we use the egyptian number system?
- Why do indicators don't change their colour in neutral substance?
- Why coconut trees don't grow in Canada or in its provinces?
- Feeling Tuned Out? 9 Reasons Why Men Don’t Listen
