Given an undirected and disconnected graph G(V, E), print its BFS traversal.
Here you need to consider that you need to print BFS path starting from vertex 0 only.
V is the number of vertices present in graph G and vertices are numbered from 0 to V-1.
E is the number of edges present in graph G.
Note : 1. Take graph input in the adjacency matrix.
2. Handle for Disconnected Graphs as well
Input Format :
Line 1: Two Integers V and E (separated by space)
Next 'E' lines, each have two space-separated integers, 'a' and 'b', denoting that there exists an edge between Vertex 'a' and Vertex 'b'.
Output Format :
BFS Traversal (separated by space)
Constraints :
2 <= V <= 1000
1 <= E <= 1000
Sample Input 1:
4 4
0 1
0 3
1 2
2 3
Sample Output 1:
0 1 3 2
Please tell what is wrong in the code.
Here is the code:
#include <iostream>
using namespace std;
#include <queue>
void print(int** edges, int V, int sv, bool* visited){
queue<int> pq;
pq.push(sv);
visited[sv] = true;
while(!pq.empty()){
int ans = pq.front();
cout << ans << " ";
pq.pop();
for(int i = 0; i < V; i++){
if(ans == i){
continue;
}
if(edges[ans][i] == 1 && !visited[i]){
pq.push(i);
visited[i] = true;
}
}
}
}
void BFS(int** edges, int V){
bool* visited = new bool[V];
for(int i = 0; i < V; i++){
visited[i] = false;
}
for(int i = 0; i < V; i++){
if(!visited[i]){
print(edges, V, i, visited);
}
}
delete [] visited;
}
int main() {
int V, E;
cin >> V >> E;
int**edges = new int*[V];
for(int i = 0; i < V; i++){
edges[i] = new int[V];
for(int j = 0; j < V; j++){
edges[i][j] = 0;
}
}
for(int i = 0; i < E; i++){
int f, s;
cin >> f >> s;
edges[f][s] == 1;
edges[s][f] == 1;
}
BFS(edges, V);
for(int i = 0; i < V; i++){
delete [] edges[i];
}
delete [] edges;
/*
Write Your Code Here
Complete the Rest of the Program
You have to take input and print the output yourself
*/
}
I think the only problem is a tiny mistake I see in the part you read params from command line. The algorithm itself looks good.
You need to use assignment operator = instead of comparison operator == when read edges:
edges[f][s] = 1;
edges[s][f] = 1;
Related
//Question
/*There are N seats in a row. You are given a string S with length N; for each valid i, the i-th character of S is '0' if the i-th seat is empty or '1' if there is someone sitting in that seat.
Two people are friends if they are sitting next to each other. Two friends are always part of the same group of friends. Can you find the total number of groups?
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single string S.
Output
For each test case, print a single line containing one integer ― the number of groups.*/
// my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin>>t;
int n=1e6;
for(int i=0;i<t;i++){
string g1;
cin>>g1;
int group;
group = 0;
for(int j=0;j<g1.length();j++){
if(g1[j] == '1'){
for(int h=1;h<n;h++){
if(g1[j+h] == '1'){
h++;
}else{
break;
}
group++;
}
} else{
continue;
}
}
cout<<group<<endl;
}
return 0;}
Example Input
4
000
010
101
01011011011110
Example Output
0
1
2
4
//my output
0
0
0
9
Based on sample output, you suppose to count '1's between zeros, which is the number of groups you have. Here is your implementation with small correction to do that.
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
// int n = 1e6; --> not used
for (int i = 0; i < t; i++) {
string g1;
cin >> g1;
int group;
group = 0;
for (size_t j = 0; j < g1.length(); j++) {
if (g1[j] == '1') {
group++;
//skip all '1' before the first '0'
while (g1[j] == '1' && j < g1.length())
j++;
}
else {
continue;
}
}
cout << group << endl;
}
return 0;
}
// my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
// you don't need n variable
// it is appropriate to use the length of the string instead
// it also will remove one warning for initialization
int n = 1e6;
for (int i = 0; i < t; i++) {
string g1;
cin >> g1;
int group; // you can use int group = 0; avoiding the statement below
group = 0;
// size_t stringLength = g1.length();
for (int j = 0; j < g1.length(); j++) {
if (g1[j] == '1') {
group++; // you need to add it here to starts counting
// better this way -> for (size_t h = 1; h < stringLength; h++)
for (int h = 1; h < n; h++) { // h < n && (j+h)<stringLength
if (g1[j + h] == '1') {
// you increasing h value twice - first in for statement, second here
// instead, you need to set j to j+h value
//h++;
// you just "moving" through the string till next'0'
j = j + h;
}
else {
break;
}
// this will increase group count for each next '1' in the string
// this is why you got 9 for the last string in your's example
//group++;
}
}
// this is not needed
//else {
// continue;
//}
}
cout << group << endl;
}
return 0;
}
I have a vector {42.195 42.195 39.025 40.075 34.220 42.195 39.750}. Here I want to get top 3 values just smaller than 42.195. Below is my approach.
I sorted the vector in descending order.
Initialize an output vector and a counter=0.
Then I traversed through the vector and checked if an element is not equal to 42.195. If it is so, increment the counter. If counter value is <= 3, push that element in the output vector. Once the counter value becomes greater than 3, break out of the for loop and return the output vector.
The above approach looks logically fine, but the code is not working fine while comparing each element with 42.195 value. Please help me.
#include<bits/stdc++.h>
#include<vector>
using namespace std;
int validateData(vector<float> &arr){
for(int i = 0 ; i < arr.size() ; i++){
if(arr[i] <= 0.0){
cout<<"\nInvalid data";
return -1;
}
}
return 0;
}
vector <float> getTop3(vector<float>& arr){
if(validateData(arr) == -1)
cout<<"\nCannot perform operation";
else {
vector<float> output;
int count = 0;
cout<<"Sorted values are: \n";
sort(arr.begin(), arr.end(), greater<float>());
for(int i = 0 ; i < arr.size() ; i++){
cout<<arr[i]<<" ";
}
for(int i = 0 ; i < arr.size() ; i++){
if(arr[i] != 42.195) {
count++;
if(count <= 3)
output.push_back(arr[i]);
else
break;
}
}
cout<<"\nOutput vector is\n";
for(int i = 0 ; i < output.size() ; i++){
cout<<output[i]<<" ";
}
return output;
}
}
int main(int argc, char *argv[]){
vector<float> arr;
cout<<"Arguments are:\n";
for(int i = 1 ; i < argc ; i++){
arr.push_back(stof(argv[i]));
}
for(int i = 0 ; i < arr.size() ; i++){
cout<<arr[i]<<" ";
}
cout<<"\n";
//Function call
getTop3(arr);
}
Below is the output.
std::partition followed by std::nth_element can do the job:
std::vector<float> get_top3(std::vector<float> v, float threshold)
{
auto end = std::partition(v.begin(), v.end(), [&](auto f){ return f < threshold; });
if (std::distance(v.begin(), end) <= 3) return {v.begin(), end};
std::nth_element(v.begin(), v.begin() + 3, end, std::greater<>{});
return {v.begin(), v.begin() + 3};
}
int main() {
std::vector<float> arr = {42.195, 42.195, 39.025, 40.075, 34.220, 42.195, 39.750};
for (auto f : get_top3(arr, 42.195))
std::cout << f << " ";
}
Demo
One of your issue is that: 42.195 != 42.195f.
I was working on a problem in codeforces and I have no problems in the functionality of the code but the code exceeds the memory usage. Can someone explain how to improve this? How to learn about memory management in general while programming because I didn't find anything related to that. Here's my code :
Summary of the problem: You are given 6 input numbers, the first 5 numbers should be multiplied each by another integer and the summation of them after multiplication is the sixth integer in the input. You should find all the combinations of the numbers the can be multiplied by each value in the input to seek the summation. the output is basically the sum of the integers chosen for each number in the input to be multiplied by.
#include <iostream>
#include <vector>
#ifndef MAX
#define MAX 100
#endif
using namespace std;
void storeAndFilter(vector <int> &arr,int chosenNumConst, int mypasha);
void print(vector<int> &v);
int printsum(vector<int> &v);
int main(int argc, char const *argv[])
{
//array of input options
int a1, a2, a3, a4, a5, pasha;
cin >> a1 >> a2 >> a3 >> a4 >> a5 >> pasha;
//declarations of vectors
vector<int> arrStrA1;
vector<int> arrStrA2;
vector<int> arrStrA3;
vector<int> arrStrA4;
vector<int> arrStrA5;
//sorting and filtering the vectors
storeAndFilter(arrStrA1,a1,pasha);
storeAndFilter(arrStrA2,a2,pasha);
storeAndFilter(arrStrA3,a3,pasha);
storeAndFilter(arrStrA4,a4,pasha);
storeAndFilter(arrStrA5,a5,pasha);
//cout<<"All Posibilities valid (Minimized by removing values < pasha) : "<<endl;
// print (arrStrA1);
// print (arrStrA2);
// print (arrStrA3);
// print (arrStrA4);
// print (arrStrA5);
//scores vectors
vector<int> resultsA1;
vector<int> resultsA2;
vector<int> resultsA3;
vector<int> resultsA4;
vector<int> resultsA5;
int i,j,k,l,m;
for (i=0; i < (int)arrStrA1.size(); ++i)
{
for (j=0; j < (int)arrStrA2.size(); ++j)
{
for (k=0; k < (int)arrStrA3.size(); ++k)
{
for (l=0; l < (int)arrStrA4.size(); ++l)
{
for (m=0; m < (int)arrStrA5.size(); ++m)
{
if(arrStrA1.at(i)+arrStrA2.at(j)+arrStrA3.at(k)+arrStrA4.at(l)+arrStrA5.at(m)==pasha)
{
resultsA1.push_back(arrStrA1.at(i));
resultsA2.push_back(arrStrA2.at(j));
resultsA3.push_back(arrStrA3.at(k));
resultsA4.push_back(arrStrA4.at(l));
resultsA5.push_back(arrStrA5.at(m));
}
}
}
}
}
}
//divise each term by the card value
for (int i = 0; i < (int)resultsA1.size(); ++i)
{
if (a1==0)
resultsA1.at(i) /= 1;
else
resultsA1.at(i) /= a1;
}
for (int i = 0; i < (int)resultsA2.size(); ++i)
{
if (a2==0)
resultsA2.at(i) /= 1;
else
resultsA2.at(i) /= a2;
}
for (int i = 0; i < (int)resultsA3.size(); ++i)
{
if(a3==0)
resultsA3.at(i) /= 1;
else
resultsA3.at(i) /= a3;
}
for (int i = 0; i < (int)resultsA4.size(); ++i)
{
if (a4==0)
resultsA4.at(i) /= 1;
else
resultsA4.at(i) /= a4;
}
for (int i = 0; i < (int)resultsA5.size(); ++i)
{
if(a5==0)
resultsA5.at(i) /= 1;
else
resultsA5.at(i) /= a5;
}
//Uncomment to show the table list after division
// print(resultsA1);
// print(resultsA2);
// print(resultsA3);
// print(resultsA4);
// print(resultsA5);
int scra1=printsum(resultsA1);
int scra2=printsum(resultsA2);
int scra3=printsum(resultsA3);
int scra4=printsum(resultsA4);
int scra5=printsum(resultsA5);
cout << scra1 <<" "<< scra2 <<" "<< scra3 <<" "<<scra4 <<" "<< scra5 <<endl;
return 0;
}
void print(vector<int> &v)
{
int size = v.size();
cout<<"========================"<<endl;
for (int i = 0; i < size; ++i)
cout<<v.at(i)<<endl;
cout<<"========================"<<endl;
}
int printsum(vector<int> &v)
{
int sum =0;
for (int i = 0; i < (int)v.size(); ++i)
sum += v.at(i);
return sum;
}
void storeAndFilter(vector <int> &arr,int chosenNumConst, int mypasha)
{
arr.reserve(10);
int i=0;
for (; i <= MAX; ++i)
{
arr.push_back(i*chosenNumConst);
if (arr.at(i)>mypasha)
break;
}
arr.resize(i);
}
Some stuff that I thought about:
Arrays instead of Vectors maybe better
The nested for loops may be the one that is taking too much memory
But to be clear, the nested for loops doesn't make too much calculations, they find all the combinations of 5 numbers '5 loops' to sum to a specific value. Filtering before entering the loop is applied so maybe the nested loop isn't the issue.
Max memory constrain in the problem is: 256 MB
You can use much less memory by not using all those vectors. You can just write your code like this:
// make sure we handle zero properly
auto end = [&](int num){
return num == 0 ? num : pasha/num;
};
for (auto i=0, end_i = end(a1); i <= end_i; ++i)
{
for (auto j=0, end_j = end(a2); j <= end_j; ++j)
{
for (auto k=0, end_k = end(a3); k <= end_k; ++k)
{
for (auto l=0, end_l = end(a4); l <= end_l; ++l)
{
for (auto m=0, end_m = end(a5); m <= end_m; ++m)
{
if(a1*i+a2*j+a3*k+a4*l+a5*m==pasha)
{
std::cout << i << " " << j << " " << k << " " << l << " " << m << "\n";
}
}
}
}
}
}
and it outputs all the valid results. For Example for the input 0 2 3 4 5 6 it produces
0 0 2 0 0
0 1 0 1 0
0 3 0 0 0
See working example here
I am currently doing a practice problem from the USACO 2006 Contest, which is basically the following:
Given a grid of dots and X's such as
......
..X..X
X..X..
......
..X...
find the rectangle with the biggest area such that the perimeter of
the rectangle includes no X's. For example, the rectangle denoted by
the f's is the best possibility.
.ffff.
.fX.fX
Xf.Xf.
.ffff.
..X...
Here is the original problem statement.
So far, I've written a code that runs with the correct output for 11 out of the 13 test cases, but two of the last test cases don't work. Here is my code.
#include <iostream>
using namespace std;
#define INF 0x3f3f3f3f
const int MAX = 200 + 5;
int N, M, MAXAREA = 0;
bool ok[MAX][MAX][MAX], land[MAX][MAX];
int main() {
/// read in input
// land[i][j] = 1 if there is a swampy area at (i, j)
cin >> N >> M;
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
char ch;
cin >> ch;
land[i][j] = (ch == 'X');
}
}
/// precompute crossing lines
// ok[col][row1][row2]: there are not X's from row1 to row2 in column col
for(int col = 0; col < M; col++)
for(int row1 = 0; row1 < N; row1++)
for(int row2 = row1; row2 < N; row2++) {
if(land[row2][col]) break;
else ok[col][row1][row2] = true;
}
/// run dynamic programming
// first loop through all pairs of rows
for(int row1 = 0; row1 < N; row1++) {
for(int row2 = row1; row2 < N; row2++) {
// for each pair of rows, go from left to right for columns. lhs_col = LHS column
for(int lhs_col = 0; lhs_col < M; ) {
// find the first LHS column that has no X's at all
if(!ok[lhs_col][row1][row2]) {
lhs_col++;
continue;
}
// next_col & last_col are next & last columns that are perfectly clear
int cur_col = lhs_col, next_col = INF, last_col = lhs_col;
// make sure cur_col has top and bottom vertices clear
while(cur_col < M && !land[row1][cur_col] && !land[row2][cur_col]) {
// finds the first and last column that are perfectly clear
if(ok[cur_col][row1][row2])
next_col = min(next_col, last_col = cur_col);
cur_col++;
}
// get maximum area
MAXAREA = max(MAXAREA, (row2 - row1 + 1) * (last_col - lhs_col + 1));
// if there is no next_col that is perfectly clear or the next one is itself
if(next_col == INF || next_col == lhs_col) break;
else lhs_col = next_col;
}
}
}
/// output answer
cout << MAXAREA << endl;
}
And here is one of the input cases that causes it to not work. My code outputs 966 while it should be 1488. The other test case is so large, there is no point in pasting it here. I'd greatly appreciate any help. Thank you so much!
I want to write a program that stores the sum of 2 numbers in an array and retrieves it in the order in which it was generated. I know that map stores the key in sorted order. Unordered_map stores the keys in an order which is definitely not based on sequence of generation.
Is there some way i can use STL to get what i want in c++ ?
Below is my code for the program. I need to find an array of 4 numbers where A+B = C+D such that all are unique and are lexicographically sorted.
Array = 1 3 3 3 3 2 2
I should get 0 1 6 7 as output but instead i am getting 1 5 2 6.
vector<int> Solution::equal(vector<int> &A) {
vector<int> result;
unordered_map<int,vector<vector<int>>> hash;
int n = A.size();
for(int i = 0; i < n ; i++) {
for(int j = i+1; j < n; j++) {
int sum = A[i] + A[j];
vector<int> temp{i,j};
if (hash.find(sum) != hash.end()) {
hash[sum].push_back(temp);
}
else
hash.insert(make_pair(sum,vector<vector<int>>{temp}));
}
}
for(unordered_map<int,vector<vector<int>>>::iterator it=hash.begin(); it != hash.end(); it++) {
int size = it->second.size();
bool found = 0;
if( size > 1) {
for(int i = 1; i < size; i++) {
cout<<it->first<<" ";
if (it->second[0][0] == it->second[i][0] || it->second[0][1] == it->second[i][0] || it->second[0][1] == it->second[i][1]) continue;
result.push_back(it->second[0][0]);
result.push_back(it->second[0][1]);
result.push_back(it->second[i][0]);
result.push_back(it->second[i][1]);
found = 1;
break;
}
if (found) break;
}
}
return result;
}