- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- What are some signs that tell me that I don't have enough protein in my diet?
- Why Don't Transformers Work on DC Supply?
- What are the best new products or inventions that most people don't know about?
- Why I don’t get that feel when I say any swear word (gaali) in English?
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C++
- Don’t Miss the Milestones – Sequence the Activities
- Why don’t we create green top pitches in India?
- Why do the two oceans in Alaska don't mix?
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C programming
- Find records from one MySQL table which don't exist in another?
- MySQL stored procedure parameters don't seem to work with special character @?
- Why python for loops don't default to one iteration for single objects?
- How can we follow "Don't think about work at home"?
- I don’t want configuration information to be transferred with the database in SAP ABAP
- Despite working/living in one company/community why does it happen that two people don't speak to each other without any specific reason?