- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to find tram lines we are in in different trips
Suppose we have a nested list with n sub-lists L. There are several stops on a tram track. Among them only n stops we have seen. L[i] contains another list and the size of L[i] list determines the number of tram lines on that stop. The values of L[i] list is line numbers, and they can be in arbitrary order. We have to find what are the possible lines of the tram we were in?
Problem Category
Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can.
So, if the input of our problem is like L = [[1, 4, 6], [1, 4], [10, 5, 6, 4, 1]], then the output will be [1, 4]
Steps
To solve this, we will follow these steps −
Define an array cnt of size: 101 and fill with 0 n := size of L for initialize i := 1, when i <= n, update (increase i by 1), do: r := size of L[i - 1] for initialize j := 1, when j <= r, update (increase j by 1), do: x := L[i - 1, j - 1] (increase cnt[x] by 1) for initialize i := 0, when i < 100, update (increase i by 1), do: if cnt[i] is same as n, then: print i
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(vector<vector<int>> L){ int n, x, r, cnt[101] = { 0 }; n = L.size(); for (int i = 1; i <= n; i++){ r = L[i - 1].size(); for (int j = 1; j <= r; j++){ x = L[i - 1][j - 1]; cnt[x]++; } } for (int i = 0; i < 100; i++){ if (cnt[i] == n){ cout << i << ", "; } } } int main(){ vector<vector<int>> L = { { 1, 4, 6 }, { 1, 4 }, { 10, 5, 6, 4, 1 } }; solve(L); }
Input
{ { 1, 4, 6 }, { 1, 4 }, { 10, 5, 6, 4, 1 } }
Output
1, 4,