I am getting segmentation for the last test case (Don't know what it is ) while solving the problem GREATESC.
Concept of the problem is basic bfs. Given an undirected graph |V| <= 3500 and |E| <= 1000000
Find the minimum distance between two given vertices.
Here's the problem link http://opc.iarcs.org.in/index.php/problems/GREATESC
Here's my solution link
http://ideone.com/GqTc6k
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#define Pi 3.14159
#define vi vector<int>
#define pi pair<int,int>
#define si stack<int>
typedef long long int ll;
using namespace std;
bool b[3501][3501]={0};
int main ()
{
int n,m;
cin >>n>>m;
int u,v;
for (int i =1;i<= m;i++)
{
scanf("%d",&u);
scanf("%d",&v);
b[u][v]=b[v][u]=1;
}
// input completed.
int dist[n+1];
int h,V;
cin >>h>>V;
dist[h]=0;
//cout<<"hero "<<h<<" "<<V<<endl;
queue<int> q;
bool bfs[3501];
for (int i=1;i<= n;i++)bfs[i]=1;
q.push(h);
bfs[h]=0;
while (!q.empty())
{
int top = q.front();
// cout<<top<<endl;
q.pop();
for (int i = 1 ;i <= 3500;i++)
{
if(bfs[i] && b[i][top])
{
int x = i;
dist[i] = dist[top] +1;
if(x == V){cout<<dist[x]<<endl;return 0;}
bfs[x]=0;
q.push(x);
}
}
}
cout<<0<<endl;
}
You have this:
cin >>n>>m;
...
int dist[n+1];
Hence the array dist may have size less than 3500. But:
for (int i = 1 ;i <= 3500;i++)
...
dist[i] = dist[top] +1;
This code might be indexing outside of dist.
You seem to need in general to be more careful that when indexing into an array, you're inside the bounds of the array.
Consider using std::vector instead of arrays, then indexing with at to get bounds checking. Or alternatively, manually assert that values are within range:
#include <assert.h>
...
for (int i = 1 ;i <= 3500;i++)
...
assert(i >= 0 && i <= n && top >= 0 && top <= n);
dist[i] = dist[top] +1;
Related
#include <iostream>
#include <set>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
//Create a set object to store a set of 200 randomly generated numbers from 1 to 10000. Use the for_each function and an anonymous function to display all the even numbers in the set.
using namespace std;
template <typename t>
void prints(t even) {
void prints(t even) {
if (even % 2) == 0;
cout << "All the even numbers in the set are: " << even;
}
}
int main()
{
srand(time(0));
set<int> nums;
for (int i = 0; i < 200; i++) {
nums.insert(rand() % 10000 + 1);
}
int gt50 = count_if(nums.begin(), nums.end(), [](int n) {return (n % 2) == 0}); // this is the issue it says I need ;, but when I put it nothing works.
for_each(nums.begin(), nums.end(), prints<int>);
}
I do not understand why, at the end of line 32 it is asking me to Implement the ; command to end of a line when I do so it still proceeds to give me the same issue. Regardless I don't understand why thats doing what its doing as I've used my debugger but cannot find anything out.
If you run your compiler, it will show you several errors:
So, the compiler tells you the problem and where it is.
Then, after removing they problematic issues and correcting semantic bug in the for loops condition, you will get:
#include <iostream>
#include <set>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
//Create a set object to store a set of 200 randomly generated numbers from 1 to 10000. Use the for_each function and an anonymous function to display all the even numbers in the set.
using namespace std;
template <typename t>
void prints(t even) {
if ((even % 2) == 0)
cout << even << '\n';
}
int main()
{
srand((unsigned int)time(0));
set<int> nums;
for (int i = 0; nums.size() < 200; i++) {
nums.insert(rand() % 10000 + 1);
}
int gt50 = count_if(nums.begin(), nums.end(), [](int n) {return (n % 2) == 0; }); // this is the issue it says I need ;, but when I put it nothing works.
for_each(nums.begin(), nums.end(), prints<int>);
}
This will work.
I'm trying to write a program in which at each step of a loop I create an adjacency list representing a graph that changes in time.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/exponential_distribution.hpp>
using namespace std;
using std::vector;
typedef boost::mt19937_64 ENG; // use Mersenne Twister 19937 as PRNG engine
typedef boost::uniform_int<> DIST_INT; // define uniform distribution of integers
typedef boost::uniform_real<> DIST_REAL; // define uniform distribution of reals on [0,1)
typedef boost::exponential_distribution<> DIST_EXP; // define exponential distribution
typedef boost::variate_generator<ENG,DIST_INT> VARIATE_INT;
typedef boost::variate_generator<ENG,DIST_REAL> VARIATE_REAL;
typedef boost::variate_generator<ENG,DIST_EXP> VARIATE_EXP;
int main()
{
const unsigned int random_seed = time(NULL);
// ======= initialize BOOST machines
ENG eng(random_seed);
DIST_INT dist_int;
DIST_REAL dist_rand(0,1);
DIST_EXP dist_exp;
VARIATE_INT randint(eng,dist_int); //random integer. use as: randint(N)
VARIATE_REAL rand(eng,dist_rand); //random float on [0,1[. use as: rand()
VARIATE_EXP randexp(eng,dist_exp); //random exponentially distributed float.
int N = 500, Tmax=200000, v, w;
float p = 0.2, s;
vector<vector<int> > contact_list;
for(int i = 0; i < 200000; i++)
{
contact_list.resize(N, vector<int>());
v = 1;
w = -1;
while(v < N)
{
s = rand();
w += 1 + int(log(1-s)/log(1-p));
while((w >= v) && (v < N))
{
w = w - v;
v += 1;
}
if (v < N)
{
contact_list[v].push_back(w);
contact_list[w].push_back(v);
}
}
}
}
However at some point I get segmentation fault. In fact I think this may not be the correct way to overwrite a vector. I also add that I would like to change N_nodes at each step. Any help is appreciated!
For the segmentation fault part you can use Valgrind to try and find out what operation in your code is writing at an invalid location.
Also you can catch Segmantation fault, with the use of signal, but it's not a good practice to catch a segmentation fault
I have written following to solve following problem
"Given a list of unsorted numbers, can you find the numbers that have the smallest absolute difference between them? If there are multiple pairs, find them all."
Here is code
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int* smallestDiff(vector<int> a,int &noOfPairs)
{
sort(a.begin(),a.end());
int * arr = new int(a.size()* sizeof(int) *2);
bool bfoundDiff = false;
int smallestDiff =0;
int num1,num2;
for(size_t i=0;i<a.size()-1;i++)
{
num1 = a[i];
num2 = a[i+1];
int newDiff = num2-num1;
if(!bfoundDiff || newDiff < smallestDiff)
{
smallestDiff = newDiff;
arr[0] = num1;
arr[1]= num2;
noOfPairs = 1;
bfoundDiff = true;
}
}
for(size_t i=0;i<a.size()-1;i++)
{
num1 = a[i];
num2 = a[i+1];
int newDiff = num2-num1;
if(newDiff == smallestDiff && num1!=arr[0] && num2!=arr[1])
{
arr[noOfPairs*2] = num1;
arr[noOfPairs*2 + 1] = num2;
++noOfPairs;
}
}
return arr;
}
int main() {
int _a_size;
cin >> _a_size;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
vector<int> _a;
int _a_item;
for(int _a_i=0; _a_i<_a_size; _a_i++) {
cin >> _a_item;
_a.push_back(_a_item);
}
int noOfPairs=0;
int *result =smallestDiff(_a,noOfPairs);
int noOfelems = noOfPairs*2;
for(int i=0;i<noOfelems;++i)
{
cout<< *(result+i)<<" ";
}
return 0;
}
Now program is running fine as per logic but its crashing when it tries to print result values.I dont see anything wrong with passing pointer as return type.
Do you guys see any issue here?
You've made a typo in the following line:
int * arr = new int(a.size()* sizeof(int) *2);
It should be like this:
int * arr = new int[a.size()* sizeof(int) *2];
Instead of allocating an array you allocate single integer and initialize it with what you think had to be size.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I count all the "prime" numbers instead of displaying them?
Example:
cout << "there are 125 prime numbers";
I'm using the number 1000 because I want to find out how many prime numbers it has.
I don't want to display the found prime numbers but I want to know how many have been found.
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main()
{
for (int a=2 ; a < 1000 ; a++)
{
bool prime = true;
for(int c=2 ; c*c <= a ; c++)
{
if(a % c == 0)
{
prime = false;
break;
}
}
if(prime) cout << a << " ";
}
return 0;
}
Reformatting your code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main() {
for (int a = 2; a < 1000; a++) {
bool prime = true;
for (int c = 2; c*c <= a; c++) {
if(a % c == 0) {
prime = false;
break;
}
}
if(prime) cout << a << " ";
}
return 0;
}
Instead of printing it out each time through the loop, you need to make a variable to count each time the number is prime. Start by adding a variable outside of your outer for loop:
int main() {
int num_primes = 0;
for (int a = 2; a < 1000; a++) {
Next, instead of printing whenever a number is prime, just increment the counter:
if(prime) {
num_primes += 1;
}
Finally, just before you return from main(), print out the number of primes:
cout << num_primes << endl;
return 0;
While this definitely looks like your homework, I hope you learn something from this.
Try this,
#include < iostream>
#include < iomanip>
#include < string>
#include < sstream>
#include < fstream>
#include < math.h>
#include < stdio.h>
using namespace std;
int main()
{
int count=0;
for (int a=2 ; a < 1000 ; a++)
{
bool prime = true;
for (int c=2 ; c*c <= a ; c++)
{
if(a % c == 0)
{
prime = false;
break;
}
}
if(prime) count++;
}
cout <<"No of prime numbers : "<< count;
return 0;
}
Easy, just increment a counter instead of printing the value. You can also obtain a fairly decent approximation of Euler's totient function using the equation N/(log(N)-1)...
this is a sample of my code. i am getting the value for maximum height. but my minimum height is a garbage value. what am i doing wrong
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 0; i < MAX; i++)
{
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
else if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
cout<< minimum<< " " << maximum<< endl;
return 0;
}
}
Garbage in, garbage out. It looks like your input routine (which you didn't post) may be populating the data incorrectly. I'd look at the input data in the debugger (even if your choice of debugger is printf()).
Your code assumes that minimum is unequal to the maximum.
Solution second if should be on its own and not in else clause from first.
assuming you do initialize the array in your real code, with these modifications:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 1 /* skip 0 - already read */; i < MAX; i++)
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
// remove the else here
if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
// move outside the loop
cout<< minimum<< " " << maximum<< endl;
return 0;
}
this should be OK