I tried solving this probblem on spoj. http://www.spoj.com/problems/BUSYMAN/
Although I was able to solve it but I got a very strange error. I tried understanding the cause of it but failed. I have two codes.
///////////////////////////////////////////////////
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class activity
{
public:
int start,end;
};
bool comp(activity p, activity q)
{
if(p.end<q.end)return true;
if(p.end==q.end&&p.start<=q.start)return true;
return false;
}
int main()
{
int t;
cin>>t;
vector<activity> v;
for(int i=0;i<t;i++)
{
int n;
cin>>n;
v.resize(n);
for(int j=0;j<n;j++)cin>>v[j].start>>v[j].end;
sort(v.begin(),v.end(),comp);
int ans=0,currend=0;
for(int j=0;j<n;j++)
{
if(v[j].start>=currend){ans++;currend=v[j].end;
}
}
cout<<ans<<endl;
}
}
/////////////////////////////////////////////
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class activity
{
public:
int start,end;
};
bool comp(activity p, activity q)
{
if(p.end<q.end)return true;
if(p.end==q.end&&p.start>=q.start)return true;
return false;
}
int main()
{
int t;
cin>>t;
int n;
vector<activity> v;
for(int i=0;i<t;i++)
{
cin>>n;
v.resize(n);
for(int j=0;j<n;j++)
cin>>v[j].start>>v[j].end;
sort(v.begin(),v.end(),comp);
int ans=0,currend=0;
for(int j=0;j<n;j++)
{
if(v[j].start>=currend)
{
ans++;currend=v[j].end;
}
}
cout<<ans<<endl;
}
}
//////////////////////////////
My problem is that the first one gives segmentation fault on spoj while second one does not. The only difference between the two is the comparison function. I just happen to define the second statement of the comparison function in two different ways which are similar. But it gives me segmentation fault in the first case but not in second case.
enter image description here
In the two images above there are two codes with respective submission ids and in the third it shows seg fault for one while not for other. You can verify with the submission ids on my spoj profile as well.
Because bool comp(activity p, activity q) doesn't meet requirements of Compare see std::sort
It should be this:
bool comp(const activity& p, const activity& q)
{
return p.end < q.end || (p.end ==q.end && p.start < q.start);
}
or
struct comp {
bool operator()(const activity& p, const activity& q) const
{
return p.end < q.end || (p.end ==q.end && p.start < q.start);
}
};
or
struct comp {
bool operator()(const activity& p, const activity& q) const
{
return std::tie(p.end, p.start) < std::tie(q.end, q.start);
}
};
The rules of C++ are that the comparator for std::sort must give a strict weak ordering.
So, the comparator must return false for equal elements. However this test:
if(p.end<q.end)return true;
if(p.end==q.end&&p.start<=q.start)return true;
return false;
returns true if the elements are equal, so this is an invalid comparator.
In your second attempt:
if(p.end<q.end)return true;
if(p.end==q.end&&p.start>=q.start)return true;
return false;
This has the same problem, also causing undefined behaviour.
You can't infer anything from the observed behaviour when the code had undefined behaviour, it is just chance (perhaps depending on some detail about your compiler's particular choice of sort algorithm) as to what behaviour you get.
Changing <= to < in the first comparator would yield a valid comparator with sort order of both end and start ascending.
Related
I'm trying to write a class in c++, that presents a group of people (each person has its own row), and the numbers in the rows represent this person's friends. If person a is person's b friend, then the person b is person's b friend as well.
I came up with something like this:
class Friends {
public:
Friends(int n);
// Creates a set of n people, no one knows each other.
bool knows(int a, int b);
// returns true if the 2 people know each other
void getToKnow(int a, int b);
// Person a & b meet.
void mutualFriends(int a, int b);
// cout's the mutual friends of person a & b
void meeting(int a);
//all friends of person a also become friends
int max();
//return the person with the highest number of friends
private:
vector<vector<int>> friends;
};
Friends::Friends(int n) {
vector<vector<int>> friends;
}
bool Friends::knows(int a, int b) {
for(int i=0; i<friends[a].size(); i++) {
if (friends[a][i]==b) {
return true;
}
}
return false;
}
void Friends::getToKnow(int a, int b) {
friends[a].push_back(b);
friends[b].push_back(a);
}
void Friends::mutualFriends(int a, int b) {
for (int i=0; i<friends[a].size(); i++) {
for (int j=0; j<friends[b].size(); j++) {
if (friends[a][i]==friends[b][j])
cout << friends[a][i] <<", ";
}
}
}
void Friends::meeting(int a) {
for (int i=0; i<friends[a].size(); i++) {
for(int j=0; j<friends[a].size();j++) {
if(i!=j && i!=a && j!=a) {
getToKnow(i,j);
}
}
}
}
int Friends::max() {
int maks = 0;
for (int i=0; i<friends[i].size(); i++) {
if (friends[i].size()<friends[i+1].size())
maks = i;
}
return maks;
}
int main() {
Friends f1 (4);
f1.getToKnow(1,3);
}
So far, every time I try to add something to the vector (f.e. with the function getToKnow) the compiler can't compile the program, pointing that
friends[a].push_back(b);
friends[b].push_back(a);
is wrong. The exact information displayed is "Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)". I don't know what I'm doing wrong and if I'm using the 2d vector correctly.
In the line
Friends::Friends(int n) {
vector<vector<int>> friends;
}
you are creating a local vector of vectors which will be deallocated upon leaving the function.
What you are looking for is:
Friends::Friends(int n) {
friends.resize(n);
}
Which will allocate n vectors, allowing you to access any element below that threshold.
I'm just guessing here, but you should probably create a constructor initialize list to set the size of the member variable:
Friends::Friends(int n)
: friends(n)
{
// Empty
}
I implemented binary search in two ways and wondering which is more efficient? please help me know which is more efficient and how can it further be optimized? is time complexity remains same in both approach? I am a beginner in programming.
approach 1;
#include<iostream>
using namespace std;
bool BinarySearch(int*a,int n,int s ){
if(n==1){
if(a[0]==s)
return true;
else
return false;
}
else{
if(s<a[n/2]){
int U[n/2];
for(int i=0;i<n/2;i++){
U[i]=a[i];
}
return BinarySearch(U,n/2,s);
}
else{
int V[n-n/2];
for(int i=0;i<n-n/2;i++){
V[i]=a[i+n/2];
}
return BinarySearch(V,n-n/2,s);
}
}
}
int main(){
int array[10]={2,4,6,8,10,12,14,16,18,22};
cout<<BinarySearch(array,10,9);
}
approach 2:
#include<iostream>
using namespace std;
bool Bsearch(int arr[],int s,int l,int x){
cout<<"calling bsearch with arguments "<<s<<' '<<l<<' '<<x<<endl;
if(l==1)
return arr[s]==x;
int h=l/2;
if(x<arr[s+h])
return Bsearch(arr,s,h,x);
else
return Bsearch(arr,s+h,l-h,x);
}
int main(){
int marks[11]={17,18,20,22,24,26,28,30,32,34,36};
cout<<Bsearch(marks,0,11,32);
}
Thanks in advance for the kind help.
Other posters are correct that variable-length arrays are not good C++. If you define your main() as:
int main() {
std::array<int> marks{17,18,20,22,24,26,28,30,32,34,36};
cout<<Bsearch(marks,0,32);
}
or:
int main() {
std::vector<int> marks{17,18,20,22,24,26,28,30,32,34,36};
cout<<Bsearch(marks,0,32);
}
then you can drop the pointer/length pair in the parameter list to your binary-search function. The function prototype becomes something like:
bool Bsearch(const std::array<int>& arr, int s, int x);
The f() function in the class MapSquare works properly.. When I add the other class MapTriple, it is not working. f() function in the MapSquare should find the square of the elements in the vector and in the MapTriple should multiply 3 to all elements.
MapGeneric is the base class which contains the function map() which is a recursive function to access the vector elements and the f() function is a pure virtual function.
MapSquare and MapTriple are two derived classes overrides the f() function to find the square of vector elements and to multiply 3 with all the vector elements.
MapSquare works properly... but when I add MapTriple, segmentation fault occures. Please help to solve this.
#include<vector>
#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class MapGeneric
{
public:
virtual int f(int){};
vector<int> map(vector<int>, int);
};
class MapSquare:public MapGeneric
{
public: int f(int);
};
class MapTriple:public MapGeneric
{
public: int f(int);
};
class MapAbsolute:public MapGeneric
{
public: int f(int);
};
vector<int> MapGeneric::map(vector<int> v, int index)
{
if(index>=1)
{
v[index]=f(v[index]);
return map(v,index-1);
}
return v;
}
int MapSquare::f(int x)
{
return x*x;
}
int MapTriple::f(int x)
{
return 3*x;
}
int MapAbsolute::f(int x)
{
return abs(x);
}
int main()
{
//mapping square
MapSquare ob;
vector<int> L,L1,L2;
for (int i = 1; i <= 5; i++)
L.push_back(i);
L1=ob.map(L,sizeof(L));
cout<<"Square = ";
for ( vector<int>::iterator i = L1.begin(); i != L1.end(); ++i)
cout << *i<<" ";
//mapping triple
MapTriple t;
L2=t.map(L,sizeof(L));
cout<<endl<<"Triple = ";
for(vector<int>::iterator i=L2.begin();i!=L2.end();++i)
cout<<*i<<" ";
return 0;
}
A number of problems here. It looks as though you think that C++ indices start at 1, rather than zero?
if(index>=1)
{
v[index]=f(v[index]);
return map(v,index-1);
}
To me that immediately looks wrong, surely you mean:
// use size_t for indices (which cannot be negative)
vector<int> MapGeneric::map(vector<int> v, size_t index)
{
// make sure the index is valid!
if(index < v.size())
{
v[index] = f(v[index]);
return map(v, index - 1);
}
return v;
}
Secondly, the sizeof() operator does not do what you expect!! It returns the size of std::vector (which is usually 24bytes on 64 bit systems - basically 3 pointers). You should use the size() method to determine the length of the array.
// remember that indices are zero based, and not 1 based!
L1=ob.map(L, L.size() - 1);
I am solving Critical links problem on UVA.The problem is about finding the bridges in the Graph.I used the same algorithm here.But I am continuously getting wrong answer.
Please suggest what's wrong with my code.
//Bridges in a Graphs
#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<stack>
#include<utility>
#include<cstdlib>
#include<algorithm>
using namespace std;
#define MAX 205
int parent[MAX],timer=0,low[MAX],disc[MAX];
bool vis[MAX];
vector<pair<int,int> >st;
vector<vector<int> >G(MAX);
bool cmp(const pair<int,int> a,pair<int,int> b)
{
if(a.first==a.second)
return a.second<b.second;
else
return a.first<b.first;
}
void reset()
{
st.clear();
memset(parent,-1,sizeof parent);
memset(vis,false,sizeof vis);
for(int i=0;i<=MAX;i++)
G[i].clear();
}
void dfs(int u)
{
vis[u]=true;
disc[u]=low[u]=timer++;
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(!vis[v])
{
parent[v]=u;
dfs(v);
low[u]=min(low[u],low[v]);
if(low[v]>low[u])
st.push_back(make_pair(min(u,v),max(u,v)));
}
else if(v!=parent[u])
low[u]=min(low[u],disc[v]);
}
}
int main()
{
int n,t=0;
while(cin>>n)
{
reset();
if(t>0)
cout<<endl;
if(n==0)
{
cout<<"0"<<" critical links\n";break;
}
int node,count;
for(int j=0;j<n;j++)
{
scanf("%d (%d)",&node,&count);
for(int i=0;i<count;i++)
{
int x;
scanf("%d",&x);
G[node].push_back(x);
G[x].push_back(node);
}
}
for(int i=0;i<n;i++)
{
if(!vis[i])
dfs(i);
}
sort(st.begin(),st.end(),cmp);
cout<<st.size()<<" critical links\n";
for(int i=0;i<st.size();i++)
cout<<st[i].first<<" - "<<st[i].second<<endl;
t++;
}
}
Finally I got it,little bit flaw in std::sort cmp function and it is
bool cmp(const pair<int,int> a,pair<int,int> b)
{
if(a.first==b.first)
return a.second<b.second;
else
return a.first<b.first;
}
also in dfs function low[v]>disc[u] instead of low[v]>low[u].
Suppose we have the following problem - we want to read a set of (x, y) coordinates and a name, then sort them in order, by increasing the distance from the origin (0, 0). Here is an algorithm which use simplest bubble sort:
#include<iostream>
#include <algorithm>
using namespace std;
struct point{
float x;
float y;
char name[20];
};
float dist(point p){
return p.x*p.x+p.y*p.y;
}
void sorting(point pt[],int n){
bool doMore = true;
while (doMore) {
doMore = false; // Assume no more passes unless exchange made.
for (int i=0; i<n-1; i++) {
if (dist(pt[i]) > dist(pt[i+1])) {
// Exchange elements
point temp = pt[i]; pt[i] = pt[i+1]; pt[i+1] = temp;
doMore = true; // Exchange requires another pass.
}
}
}
}
void display(point pt[],int n){
for (int i=0;i<n;i++){
cout<<pt[i].name<< " ";
}
}
int main(){
point pts[1000];
int n=0;
while (cin>>pts[n].name>>pts[n].x>>pts[n].y){
n++;
}
sorting(pts,n);
display(pts,n);
return 0;
}
But I want to write STL sorting algorithm instead of bubble sort. How to do so?
I mean that, how should I use dist function in STL sort algorithm?
The STL sort function std::sort can take a user-defined comparison function (or function object) as an optional third argument. So if you have your items in e.g.:
vector<point> points;
You can sort them by calling:
sort(points.begin(), points.end(), my_comp);
where my_comp() is a function with the following prototype:
bool my_comp(const point &a, const point &b)
#include <algorithm>
bool sort_by_dist(point const& p1, point const& p2) {
return dist(p1) < dist(p2);
}
...
std::sort(pt, pt + n, sort_by_dist);