Tag Archives: STL

c++ STL map

dictionary data structure.

 

example with question answer :

Problem
Given names and phone numbers, assemble a phone book that maps names to their respective phone numbers.

After this dictionary is created you will then be given an unknown number of names to query your phone book for; for each queried, print the associated entry from your phone book (in the form name=PhoneNumber ) or  ( Not Found) if there is no entry for .

Input Format

The first line contains an integer,N , denoting the number of entries in the phone book.
Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend’s , and the second value is an -digit .

After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input.

 

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
cin>>N;
map<string,int> dict;
for(int i = 0; i < N; i++){
string name;
int number;
cin>>name;
cin>>number;
dict[name] = number;
}
string line;
vector<string> inp;
//remove top new line
getline(std::cin, line);
while (getline(std::cin, line)){
inp.push_back(line);
}
for(int i = 0; i < inp.size(); i++){
if(dict.find(inp[i]) != dict.end()){
cout<<inp[i]<<"="<<dict[inp[i]]<<endl;
}
else{
cout<<"Not found"<<endl;
}
}
return 0;
}

Advertisements

Heap in cpp stl

make_heap: rearrange elements in a range such that they form a heap

 

make_heap(begin,end, comparator)

comparator is a boolean function optional

pop_heap

push_heap

if v is a vector then

std::make_heap (v.begin(),v.end());

v.front() will give you maximum [default is maxheap without comparator]

You can pass the comparator function to each operation to maintain the heap property.

get the element by v.front()

Now pop the element using

pop_heap (v.begin(),v.end()); // can also pass comparator here 
Pop element from heap and rearranges the elements in the heap range [first,last) in such a way that the part considered a heap is shortened by one: The element with the highest value is moved to (last-1).
While the element with the highest value is moved from first to (last-1) (which now is out of the heap), the other elements are reorganized in such a way that the range [first,last-1) preserves the properties of a heap.
Now to actually remove the element from the vector you can use:

v.pop_back();

So a range can be organized into a heap by calling make_heap. After that, its heap properties are preserved if elements are added and removed from it using push_heap and pop_heap, respectively.


pop_heap (v.begin(),v.end()); v.pop_back();
  std::cout << "max heap after pop : " << v.front() << '\n';

 

push_heap (v.begin(),v.end());

Given a heap in the range [first,last-1), this function extends the range considered a heap to [first,last) by placing the value in (last-1) into its corresponding location within it.

 v.push_back(99); std::push_heap (v.begin(),v.end()); std::cout << "max heap after push: " << v.front() << '\n'; 

C++ STL std::array

A hybrid between c array and cpp vector but with lot of difference. Size has to be known at compile time. It can’t be dynamic.

Initialized as


std::array myarray;

5 is the size of the array must be known at compile time. You can access elements by [] (array) operator but this will not give in size check. For size check use at operator.


myarray.at(i)

myarray.size()

sort(myarray.begin(),myarray.end(), comparator)

Prim’s MST (Minimum Spanning Tree)

Given a graph with N nodes and M edges (Undirected) with positive weights. Find the minimum spanning tree. A tree with minimum overall weight edge. This is cover all nodes of the original graph if possible. You will be given a starting point S. Just in case the graph is not connected. Then you can find the MST which contains S.

 

Input Format

First line has two integers , denoting the number of nodes in the graph and , denoting the number of edges in the graph.

The next lines each consist of three space separated integers , first two integers are the two nodes between which the  edge exists, last/third integer is the weight of the edge.

The last line has an integer , denoting the starting node.

Nodes are numbered from 1 to N.

There can be multiple edges between same pair of nodes. Consider them as multiple edges.

 

Sample input:

3 3
1 2 2
1 3 3
3 2 6
1

Sample Output

5

 

Solution:

</pre>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

struct edge{
int begin;
int end;
int weight;
};
//minHeap
bool comp(const edge& a, const edge& b){
return (a.weight > b.weight);
}

void print(edge e){
cout<<e.begin<<" -> "<<e.end<<" w: "<<e.weight<<endl;
}
void prims(vector <vector <edge> > &adj, int start, int V){
vector <edge> minHeap;
int result = 0;
for(int i = 0; i < adj[start].size(); i++){
minHeap.push_back(adj[start][i]);
//print(adj[start][i]);
}
make_heap (minHeap.begin(),minHeap.end(), comp);
vector <bool> visited(V);
visited[start] = true;
while(!minHeap.empty()){
edge e = minHeap.front();
//cout<<"popped ";
//print(e);
pop_heap(minHeap.begin(), minHeap.end(),comp);
minHeap.pop_back();
if(!visited[e.end]){
visited[e.end] = true;
result += e.weight;
//cout<<"res: "<<result<<endl;
for(int i = 0; i < adj[e.end].size(); i++){
minHeap.push_back(adj[e.end][i]); push_heap(minHeap.begin(), minHeap.end(), comp);
//cout<<"push ";
//print(adj[e.end][i]);
}
}
}
cout<<result<<endl;
}

int main() {
int V, E, S;
cin>>V;
cin>>E;
vector <vector <edge> > adj(V);
for(int i = 0; i < E; i++){
int start, end, weight;
cin>>start;
cin>>end;
cin>>weight;
start--;end--;
edge e1;
e1.end = end;
e1.weight = weight;
e1.begin = start;
adj[start].push_back(e1);
edge e2;
e2.end = start;
e2.weight = weight;
e2.begin = end;
adj[end].push_back(e2);
}
cin>>S;
S--;
prims(adj,S, V);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}

Max Sum

Given an array of positive numbers, find the maximum sum of a sub-sequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].

Output:

Print the maximum sum of a sub-sequence.

 

C++ Solution


#include <iostream>
#include <vector>

using namespace std;

/*
T denotes maxsum then
T(N) = max(A[N-1] + T(N-2), T(N-1))
*/
void printMaxSum(vector <int> inp)
{
int size = inp.size();
vector <int> maxSum;
if(size <= 0)
return;
else
{
if(size == 1)
{
cout<<inp[0]<<endl;
return;
}
else
{
maxSum.push_back(inp[0]);
maxSum.push_back(max(inp[0],inp[1]));
}
}
for(int i = 2; i < size; i++)
{
int included = inp[i] + maxSum[i - 2];
int excluded = maxSum[i-1];
maxSum.push_back(max(included,excluded));
}
cout<< maxSum[size-1]<<endl;
}

int main() {
int T = 0;
//read number of test cases
cin>>T;
vector < vector <int> > allInputs;
for (int i = 0; i < T; i++)
{
int N = 0;
cin>>N;
//read all N inputs in a vector
vector <int> arr;
for(int j = 0; j < N; j++)
{
int inp = 0;
cin>>inp;
arr.push_back(inp);
}
allInputs.push_back(arr);
}

for(int i = 0; i < T; i++)
{
printMaxSum(allInputs[i]);
}

return 0;
}