C++ Error in summing vector - c++

Task:
In a 6x6 array, 16 3x3 array can be constructed. Find the largest sum of the 3x3 array (Source: https://www.hackerrank.com/challenges/30-2d-arrays/problem)
Example:
The largest 3x3 array is
2 4 4
0 2 0
1 2 4
So we print out 19
My Code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
int main()
{
vector< vector<int> > arr(6,vector<int>(6));
for(int arr_i = 0;arr_i < 6;arr_i++){
for(int arr_j = 0;arr_j < 6;arr_j++){
cin >> arr[arr_i][arr_j];
}
}
int maxVal = 0;
for (int y = 2; y < 6; y++)
{
for (int x = 2; x < 6; x++)
{
if ( y >=2 && x >=2)
{
int vert = y;
int hori = x;
int first = arr[vert-2][hori] + arr[vert-2][hori-1] + arr[vert-2][hori-2];
int second = arr[vert-1][hori-1] ;
int third = arr[vert][hori] + arr[vert][hori-1] + arr[vert][hori-2];
int sum = first + second + third;
if (sum > maxVal)
maxVal = sum;
}
}
}
cout << maxVal;
}
Edit:
I misunderstood the question, but I fixed the problem. Later on, I still got incorrect test-cases. The original solution seems to be wrong.
Problem: When I submit the code, some of test case return the wrong answer. I tried reading the code and nothing seems wrong.

The problem from the provided link is not about the 3x3 submatrices but about the hourglass shapes:
a b c
d
e f g
In order to get the correct values; your sum of the second row should be:
int second = arr[vert-1][hor-1]
And also, there is no need for the if statement as someone already mentioned in the comments.

Here is a cleaner code. Start from [1][1] and iterate till [length-1][length-1]. And on each iteration, calculate the sum of the surrounding hourglass.
Also, note that you need to sum the hourGlass and NOT the 3x3 subArray.
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
int main()
{
// user input
//vector< vector<int> > myVector(6,vector<int>(6));
//for(int arr_i = 0;arr_i < 6;arr_i++)
// for(int arr_j = 0;arr_j < 6;arr_j++)
// cin >> myVector[arr_i][arr_j];
// sample input
vector<vector<int>> myVector = {
{ { 1 },{ 1 },{ 1 },{ 0 },{ 0 },{ 0 } },
{ { 0 },{ 1 },{ 0 },{ 0 },{ 0 },{ 0 } },
{ { 1 },{ 1 },{ 1 },{ 0 },{ 0 },{ 0 } },
{ { 0 },{ 0 },{ 2 },{ 4 },{ 4 },{ 0 } },
{ { 0 },{ 0 },{ 0 },{ 2 },{ 0 },{ 0 } },
{ { 0 },{ 0 },{ 1 },{ 2 },{ 4 },{ 0 } },
};
int maxVal = -9999; // start with big negative
for (int y = 1; y < 5; y++)
{
int sum = 0;
for (int x = 1; x < 5; x++)
{
sum = myVector[y - 1][x - 1] + myVector[y - 1][x] + myVector[y - 1][x + 1]; // first row of the hourglass
sum += myVector[y][x]; // second row
sum += myVector[y + 1][x - 1] + myVector[y + 1][x] + myVector[y + 1][x + 1];// third row
if (sum > maxVal)
maxVal = sum;
}
}
cout << maxVal << endl;
system("pause");
return 0;
}

Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
int main(){
int arr[7][7], sum[17], l = 0;
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
cin >> arr[i][j];
}
}
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
sum[l] = 0;
sum[l] = sum[l] + arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j] + arr[i+1][j+1] + arr[i+1][j+2]+ arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2];
l++;
}
}
sort(sum, sum + 17);
cout << sum[16];
}
Explanation
This is a simple problem with small values, so we do not need dynamic programming(YAY!).
Vectors are also quite useless here when we can do it correctly with arrays.
Basically I search every set of 3x3 squares, and find the maximum sum. Hope this helps!

Related

C++ display possible bishop moves in an empty chess board

This task asks to display possible bishop moves in a chessboard (8 x 8) as in an example shown below:
x = 4, y = 4
1 0 0 0 0 0 1 0,
0 1 0 0 0 1 0 0,
0 0 1 0 1 0 0 0,
0 0 0 2 0 0 0 0,
0 0 1 0 1 0 0 0,
0 1 0 0 0 1 0 0,
1 0 0 0 0 0 1 0,
0 0 0 0 0 0 0 1
Image for clear understanding
#include <iostream>
using namespace std;
int main() {
int array[8][8], x , y;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
array[i][j] = 0;
}
}
cout << "Input x coordinate: ";
cin >> x;
cout << "Input y coordinate: ";
cin >> y;
for (int i = 0; i < 8; i++)
{ // 1st diagonal
array[x + i][y + i] = 1;
array[x - i][y - i] = 1;
}
for (int i = 0; i < 8; i++)
{ // 2nd diagonal
array[x + i][y - i] = 1;
array[x - i][y + i] = 1;
}
array[x][y] = 2;
for (int i = 0; i < 8; i++) //Cout
{
for (int j = 0; j < 8; j++)
{
cout << array[i][j];
}
cout << endl;
}
return 0;
}
It seems to work only with 1st diagonal
This is more of an algorithm/math answer than C++.
Suppose the grid's bottom left point is the origin (i.e. i = 0, j = 0), and the coordinate of the top right point in the grid is i=7, j=7.
A bishop that is on i=0, j=0 can hit anything on these two lines:
i = j and i = - j
When you put the bishop at point x, y instead of 0,0, these lines change to:
i - x = j - y and i - x = - (j - y)
Now, you can iterate all points in the matrix and check which ones satisfy the line equation:
int main() {
int x, y;
std::cout << "Input x coordinate: ";
std::cin >> x;
std::cout << "Input y coordinate: ";
std::cin >> y;
int array[8][8];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if ((i - x == j - y) || (i - x == -(j - y))) {
array[i][j] = 1;
} else {
array[i][j] = 0;
}
}
}
array[x][y] = 2;
// We should print the matrix from top to bottom.
// j represents the y coordinate, and i represents the x coordinate.
for (int j = 7; j >= 0; j--) {
for (int i = 0; i < 8; i++) {
std::cout << array[i][j];
}
std::cout << std::endl;
}
return 0;
}
It looks like it's working for both diagonals when I run it. There is a small bug that might mess things up though. You'll want to add bounds checks like this:
for (int i = 0; i < 8; i++)
{ // 1st diagonal
if (x + i < 8 && y + i < 8)
array[x + i][y + i] = 1;
if (x - i >= 0 && y - i >= 0)
array[x - i][y - i] = 1;
}
for (int i = 0; i < 8; i++)
{ // 2nd diagonal
if (x + i < 8 && y - i >= 0)
array[x + i][y - i] = 1;
if (x - i >= 0 && y + i < 8)
array[x - i][y + i] = 1;
}
Without these bounds checks you'll be accessing elements outside of the array bounds and could be messing up other entries in the array. There are other ways to do the bounds checking, but this might be the easiest.
To illustrate the issue, assume x = 4 and then in the for loop when i = 5. When you're indexing into the array with array[x - i] that'll be the same as array[-1]. When you index into an array with a negative value you'll be messing with the wrong memory.
I would start with a very simple case.
Suppose we want to plot the diagonal matrix of size 4x4:
i 0 1 2 3
j
0 1 0 0 0
1 0 1 0 0
2 0 0 1 0
3 0 0 0 1
We have a non zero value when:
i = j (I)
Now, suppose we shift this diagonal horizontally so that the non-zero value of the first line is located at X0.
For example, for X0 = 1:
X0
i' 0 1 2 3
j'
0 0 1 0 0
1 0 0 1 0
2 0 0 0 1
3 0 0 0 0
The shifted coordinates are:
i' = i + X0 (II)
Doing the same for shifting vertically by Y0:
j' = j + Y0 (III)
With (II) and (III) in (I) we have:
i' - X0 = j' - Y0 (IV)
Now we do the same for the antidiagonal matrix:
i 0 1 2 3
j
0 0 0 0 1
1 0 0 1 0
2 0 1 0 0
3 1 0 0 0
We have a non zero value when:
j = 3 - i (V)
Shifting horizontally by X0 we have:
i' = -3 + i + X0 (VI)
Shifting vertically by Y0:
j' = j + Y0 (VII)
With (VI) and (VII) in (V):
j' - Y0 = X0 - i' (VIII)
The code just needs to check for (IV) and (VIII):
#include <iostream>
using namespace std;
int main()
{
int array[8][8] = {0,};
int x = 0;
int y = 0;
cout << "Input x coordinate: ";
cin >> x;
cout << "Input y coordinate: ";
cin >> y;
for (int j = 0; j < 8; j++)
for (int i = 0; i < 8; i++)
if ( i - x == j - y
|| j - y == x - i)
array[j][i] = 1;
array[y][x] = 2;
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < 8; i++)
cout << array[j][i];
cout << endl;
}
return 0;
}
Note that the matrix is plotted following the convention array[lines][columns], so to set cartesian coordinates we write array[y][x].

Finding minimum total length of line segments to connect 2N points

I'm trying to solve this problem by bruteforce, but it seems to run very slow when given 7 (which is 2*7 points).
Note: I only need to run it to maximum 2*8 points
Problem statement:
Given 2*N points in a 2d plane, connect them in pairs to form N line segments. Minimize the total length of all the line segments.
Example:
Input: 5 10 10 20 10 5 5 1 1 120 3 6 6 50 60 3 24 6 9 0 0
Output: 118.4
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
class point{
public:
double x, y;
};
double getLength(point a, point b){
return hypot((a.x - b.x), (a.y - b.y));
}
static double mini = INT_MAX;
void solve(vector <point> vec, double sum){
double prevSum = sum;
if(sum > mini){
return;
}
if(vec.size() == 2){
sum += getLength(vec[0], vec[1]);
mini = min(mini, sum);
return;
}
for(int i = 0; i < vec.size() - 1; i++){
for(int j = i + 1; j < vec.size(); j++){
sum = prevSum;
vector <point> temp = vec;
sum += getLength(temp[i], temp[j]);
temp.erase(temp.begin() + j);
temp.erase(temp.begin() + i);
solve(temp, sum);
}
}
}
int main(){
point temp;
int input;
double sum = 0;
cin >> input;
vector<point> vec;
for(int i = 0; i < 2 * input; i++){
cin >> temp.x >> temp.y;
vec.push_back(temp);
}
solve(vec, sum);
cout << fixed << setprecision(2) << mini << endl;
}
How can I speed up this code ?
I don't think this is what you are looking for but I mention it for completeness sake anyway. The problem can be formulated as a Mixed Integer Programming (MIP) problem.
We have distances:
d(i,j) = distance between point i and j (only needed for i<j)
and decision variables
x(i,j) = 1 if points i and j are connected (only needed for i<j)
0 otherwise
Then we can write:
Solving this problem can be done with widely available MIP solvers and leads to proven optimal solutions. A small example with 50 points:
You can solve this iteratively by using next_permutation() to go through all the permutations one by one. Apologies for the messy code, but this should show you how to do it:
struct Point {
Point(int x, int y) : x(x), y(y) {
}
bool operator< (const Point& rhs) {
const int key1 = y * 1000 + x;
const int key2 = rhs.y * 1000 + rhs.x;
return key1 < key2;
}
double dist(const Point& next) {
const double h = (double)(next.x - x);
const double v = (double)(next.y - y);
return sqrt(h*h + v*v);
}
int x, y;
};
You need the operator so you have some sort of sorting key for your points, so next_permutation can go through them in lexicographical increasing order.
double getShortestDist(std::vector p) {
double min = 200000;
std::sort(p.begin(), p.end());
while(std::next_permutation(p.begin(), p.end())) {
double sum = 0.0;
for (int i = 0; i < p.size(); i+= 2) {
sum += p[i].dist(p[i+1]);
}
if (sum < min) {
min = sum;
}
}
return min;
}
int main(int argc, char*argv[]) {
static const int arr[] = {
10, 10, 20, 10, 5, 5, 1, 1, 120, 3, 6, 6, 50, 60, 3, 24, 6, 9, 0, 0
};
std::vector<Point> test;
for (int i = 0; i < 20; i += 2) {
test.push_back(Point(arr[i], arr[i+1]));
printf("%d %d\n", arr[i], arr[i+1]);
}
printf("Output: %d, %f", test.size(), getShortestDist(test));
}

How to group sub-vector by intersect or not in C++

I have a 2d vector
vector<vector<double>> vec = { { 1, 0.5 },{ 2, 0.5 },{ 2.25, 0.5 },{ 2.6, 0.3 },
{3.3, 0.5 },{ 3, 0.5 },{ 3.1, 0.5 },{ 4, 0.6 } };
The first element is the start about a line. The second element is the length about the line. I can show it as follow graph
Now I want to get the group of the line index as they intersect or not. I mean I hope the result is
{{1},{2,3,4},{5,6,7},{8}}
If I'm in Wolfram Mathematic, I can use follow code
list = {{1, 0.5}, {2, 0.5}, {2.25, 0.5}, {2.6, 0.3}, {3.3, 0.5}, {3,
0.5}, {3.1, 0.5}, {4, 0.6}};
g = RelationGraph[#[[2]] < #2[[2]] < #[[2]] + #[[3]] || #[[2]] <
#2[[2]] + #2[[3]] < #[[2]] + #[[3]] &,
MapIndexed[Prepend[#, First[#2]] &, list]]
Map[First] /# ConnectedComponents[g]
But how to implement this in C++?
In this problem, what you basically need to do is group all the intervals together, that overlap or intersect directly or indirectly.
Let's assume that we converted (start, len) pairs to (start, end) pairs. So, now we have a list of (start, end). If we sort this list by start time and iterate over it. Then:
if : means that the ith range is disjoint from any range uptil i-1. So, add it to a new group.
if : means that the ith range is overlapping/intersecting with some of the range(s) in 1..i-1.
Note: is the max value of end time from 1 to i-1.
I've added rest of the explanation in the form of comments, in the code itself.
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//a struct representing a range
struct range {
double st, ed;
};
//just a shorthand :p
using prp = pair<range, int>;
/*
* Comparator that sorts by the start time of range.
* If start times are equal, then end time is used to sort.
*/
inline bool sort_by_start(const prp &a, const prp &b) {
if (a.first.st == b.first.st) return a.first.ed < b.first.ed;
return a.first.st < b.first.st;
}
int main() {
//your vector
const vector<vector<double>> v2d = { { 1, 0.5 }, { 2, 0.5 }, { 2.25, 0.5 }, { 2.6, 0.3 },
{3.3, 0.5 }, { 3, 0.5 }, { 3.1, 0.5 }, { 4, 0.6 }
};
//a vector of ranges
//each element is pair of (range, position) where position is the
//original index of range in v2d
vector<prp> rng(v2d.size());
//a vector of vector of ints that will hold the groups
vector<vector<int>> idx;
int i, j;
//building ranges. end time = start time + length
//position is stored, so that it can be used later.
for (i = 0; i < (int) v2d.size(); ++i) {
rng[i] = {{v2d[i][0], v2d[i][1] + v2d[i][0]}, i};
}
//sorting by start time
sort(rng.begin(), rng.end(), sort_by_start);
//starting of first group
idx.push_back(vector<int>());
idx.back().push_back(rng[0].second);
double edv = rng[0].first.ed;
for (i = 1; i < (int)rng.size(); ++i) {
//if next start time is greater than the largest
//end time encountered so far (maintained using edv)
//it means the next group is starting, so push an empty vector
if (edv < rng[i].first.st)
idx.push_back(vector<int>());
//edv maintains the largest end time encountered so far.
edv = max(edv, rng[i].first.ed);
//we want to push the current range into the last active group.
//why last? because they are all sorted by start-time.
idx.back().push_back(rng[i].second);
}
//displaying
for (i = 0; i < (int)idx.size(); ++i) {
for (j = 0 ; j < (int)idx[i].size(); ++j) {
cout << idx[i][j] + 1 << ' ';
}
cout << '\n';
}
return 0;
}
Result:
1
2 3 4
6 7 5
8
Done!
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<vector<int>> group_digit(vector<vector<int>> component)
{
class interval_intersectionQ
{
public:
bool operator()(vector<vector<int>> sub_group, vector<int> vec)
{
vector<int> continuous_line;
for (vector<int> i : sub_group)
{
continuous_line.push_back(i[1]);
continuous_line.push_back(i[1] + i[2]);
}
pair<vector<int>::iterator, vector<int>::iterator> interval = minmax_element(continuous_line.begin(), continuous_line.end());
if (*interval.first <= vec[1] && vec[1] <= *interval.second ||
*interval.first <= vec[1] + vec[2] && vec[1] + vec[2] <= *interval.second ||
vec[1] <= *interval.first && *interval.first <= vec[1] + vec[2] ||
vec[1] <= *interval.second && *interval.second <= vec[1] + vec[2])
{
return true;
}
else
{
return false;
}
}
};
vector<vector<int>> origin = component;
vector<vector<vector<int>>> group;
while (!origin.empty())
{
group.push_back(vector<vector<int>>());
group[group.size() - 1].push_back(origin[origin.size() - 1]);
origin.pop_back();
for (int i = 0; i < origin.size(); i++)
{
if (interval_intersectionQ()(group[group.size() - 1], origin[i]))
{
group[group.size() - 1].push_back(origin[i]);
origin.erase(origin.begin() + i);
i = -1;
}
}
}
vector<vector<int>> one_digit(group.size());
for (int i = 0; i<group.size(); i++)
{
for (vector<int> j : group[i])
{
one_digit[i].push_back(j[0]);
}
}
return one_digit;
}
int main()
{
vector<vector<int>> origin = { { 1, 10, 5 },{ 2, 20, 5 },{ 3, 22, 5 },
{ 4, 26, 3 },{ 5, 33, 5 },{ 6, 30,5 },{ 7, 31, 5 },{ 8, 40, 6 } };
vector<vector<int>> one_digit = group_digit(origin);
for (vector<int> i : one_digit)
{
for (int j : i)
{
cout << j << " ";
}
cout << endl;
}
return 0;
}
8
7 5 6
4 3 2
1

Wall destroying

There is a wall built from numbers. 0 means there is a hole and blocks can't sit on holes. Someone has a special gun that fires all blocks with a number in one shot.
So I have a matrix called wall and have to write a gun. I wrote the program, but I have a problem and I do not understand why it is happening. In my code
#include <iostream>
#include <cstdio>
using namespace std;
int createWall( int &height, int &length, int wall[][ 100 ], int shots )
{
int i;
int j;
cin >> height;
cin >> length;
cin >> shots;
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < length; j++ )
{
cin >> wall[ i ][ j ];
}
}
return shots;
}
void wallNow( int height, int length, int wall[][ 100 ] )
{
int i;
int j;
for ( i = 0; i < height; i++ )
{
for ( j = 0; j < length; j++ )
{
cout << wall[ i ][ j ] << " ";
}
cout << "\n";
}
}
void destroyWall( int height, int length, int wall[][100], int shots )
{
int i;
int j;
int k;
int x;
int aimedBlocks;//number to be "destroyed"
//set all aimedBlocks to 0
for ( x = 0; x < shots; x++ )
{
cin >> aimedBlocks;
for ( i = 0; i < height; i++ )
{
for ( k = 0; k < length; k++ )
{
if ( wall[ i ][ k ] == aimedBlocks )
{
wall[ i ][ k ] = 0;
}
}
}
}
int counter;//I use this variable because at some point I have a 0 followed only by 0's
for ( i = 0; i < length; i++ )
{
j = height - 1;
counter = 0;
//if I find a 0 then I move all elements higher that it one step down
while ( counter < height )
{
if ( wall[ j ][ i ] == 0 )
{
for ( k = j; k > 0; k-- )
{
wall[ k ][ i ] = wall[ k - 1 ][ i ];
}
wall[ height - j - 1 ][ i ] = 0;
}
else
j--;//I don't always go up ene step because the "block" droped in place of 0 may be 0
counter++;
}
}
}
int main()
{
int height;
int length;
int wall[ 100 ][ 100 ];
int shots = 0;
shots = createWall( height, length, wall, shots );
destroyWall( height, length, wall, shots );
wallNow( height, length, wall );
}
I really do not understand why line wall[ height - j - 1 ][ i ] = 0; is working for the first 4 columns in the following example and it does not work for the last one.
Format input:
height length shots
wall_0_0 ... wall_0_length
... ... ...
wall_height ... wall_height_length
shot_0 ... shot_shots
Input:
4 5 3
3 5 4 5 1
2 1 1 5 3
1 1 5 5 1
5 5 1 4 3
1 5 1
Remove all values that matches with 1, 5, 1. And wall remains must drop into the bottom.
Output:
0 0 0 0 0
0 0 0 0 0
3 0 0 0 0
2 0 4 4 3
Expected:
0 0 0 0 0
0 0 0 0 0
3 0 0 0 3
2 0 4 4 3
Please help me solve this problem. I could not find it debugging the code.
Your algorithm is strange, I don't understand what you try to do.
A simple way to achieve your purpose is to iterate from the left to the right of your wall, then for each you iterate from the bottom to the top. Each time you get a 0, you search for a non zero value to the top and swap their if you found it.
Example (very basic could be improve):
for (size_t i = 0; i < length; i++) { // i is for iterate from left(0) to right(length - 1)
size_t j = height; // j is for iterate from bot(height - 1) to top(0)
while (j-- > 0) {
if (wall[j][i] == 0) {
size_t k = j; // k is for found a non zero value from j - 1 to the top(0)
while (k-- > 0) {
if (wall[k][i] != 0) {
wall[j][i] = wall[k][i];
wall[k][i] = 0;
break;
}
}
}
}
}
Note:
I use size_t because this is the type for index.
I recommend you to switch for std::vector and use iterator on it in C++.

Calculating Execution time and big O time of my c++ program

My Code is:
#include <iostream>
#include <utility>
#include <algorithm>
//#include <iomanip>
#include <cstdio>
//using namespace std;
inline int overlap(std::pair<int,int> classes[],int size)
{
std::sort(classes,classes+size);
int count=0,count1=0,count2=0;
int tempi,tempk=1;
for(unsigned int i=0;i<(size-1);++i)
{
tempi = classes[i].second;
for(register unsigned int j=i+1;j<size;++j)
{
if(!(classes[i].first<classes[j].second && classes[i].second>classes[j].first))
{ if(count1 ==1)
{
count2++;
}
if(classes[i].second == tempi)
{
tempk =j;
count1 = 1;
}
////cout<<"\n"<<"Non-Overlapping Class:\t";
////cout<<classes[i].first<<"\t"<<classes[i].second<<"\t"<<classes[j].first<<"\t"<<classes[j].second<<"\n";
classes[i].second = classes[j].second;
count++;
if(count1==1 && j ==(size-1))
{
j= tempk;
classes[i].second = tempi;
count1= 0;
if(count2 !=0)
{
count = (count + ((count2)-1));
}
count2 =0;
}
}
else
{
if(j ==(size-1))
{
if(count>0)
{
j= tempk;
classes[i].second = tempi;
count1= 0;
if(count2 !=0)
{
count = (count + ((count2)-1));
}
count2 =0;
}
}
}
}
}
count = count + size;
return count;
}
inline int fastRead_int(int &x) {
register int c = getchar_unlocked();
x = 0;
int neg = 0;
for(; ((c<48 || c>57) && c != '-'); c = getchar_unlocked());
if(c=='-') {
neg = 1;
c = getchar_unlocked();
}
for(; c>47 && c<58 ; c = getchar_unlocked()) {
x = (x<<1) + (x<<3) + c - 48;
}
if(neg)
x = -x;
return x;
}
int main()
{
int N;
////cout<<"Please Enter Number Of Classes:";
clock_t begin,end;
float time_interval;
begin = clock();
while(fastRead_int(N))
{
switch(N)
{
case -1 : end = clock();
time_interval = float(end - begin)/CLOCKS_PER_SEC;
printf("Execution Time = %f",time_interval);
return 0;
default :
unsigned int subsets;
unsigned int No = N;
std::pair<int,int> classes[N];
while(No--)
{
////cout<<"Please Enter Class"<<(i+1)<<"Start Time and End Time:";
int S, E;
fastRead_int(S);
fastRead_int(E);
classes[N-(No+1)] = std::make_pair(S,E);
}
subsets = overlap(classes,N);
////cout<<"\n"<<"Total Number Of Non-Overlapping Classes is:";
printf("%08d",subsets);
printf("\n");
break;
}
}
}
and Input and output of my program:
Input:
5
1 3
3 5
5 7
2 4
4 6
3
500000000 1000000000
1 5
1 5
1
999999999 1000000000
-1
Output:
Success time: 0 memory: 3148 signal:0
00000012
00000005
00000001
Execution Time = 0.000036
I tried to calculate by having clocks at start of main and end of main and found out the time.But it said only some 0.000036 secs.But when I tried to post the same code in Online Judge(SPOJ).My program got 'Time Limit Exceeded' Error. Time Limit for the above program in SPOJ is 2.365 secs.Could somebody help me figure out this?
I consider that your question is about the overlap function.
In it, you have
A sort call: O(n×ln(n))
two for loops:
the first is roughly 0..Size
the second (nested in the first) is roughly i..Size
The inside of the second loop is called Size(Size+1) / 2 (reverse sum of the N first integer) times with no breaks.
So your algorithm is O(n²) where n is the size.