my task is
1) By the quantity of solved tasks in descending order
2) When the quantities of solved tasks are equal – by the penalty time in ascending order
3) When both quantities of solved tasks and penalty times are equal – by the indices of teams in ascending order.
input file gonna be like this:
The first line contains a natural number n (1 ≤ n≤105) – the quantity of teams participating in the contest.
The next n lines contain two numbers S – the quantity of solved tasks (0 ≤ S ≤ 100) and the penalty time T (1 ≤ T ≤ 1000000) of the ith team.
Example:
6
3 50
5 720
1 7
0 0
8 500
8 500
so output file will be:
5 6 2 1 3 4
#include <iostream>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void printArray(int A[],int B[], int size)
{
int i,xx;
for (i = size-1; i >= 0; i--) {
for (int x = 0; x < size; x++) {
if (A[i] == B[x]) {
cout << x+1 << " ";
//break;
}
}
}
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int qarray, largest;
cin >> qarray;
int *task = new int[qarray];
int *newtask = new int[qarray];
int *time = new int[qarray];
for (int i = 0; i < qarray; i++)
{
cin >> task[i];
cin >> time[i];
}
for (int i = 0; i <= qarray - 1; i++) {
newtask[i] = task[i];
}
int i, j;
for (i = 0; i < qarray - 1; i++) {
// Last i elements are already in place
for (j = 0; j < qarray - i - 1; j++) {
if (task[j] > task[j + 1]) {
swap(&task[j], &task[j + 1]);
}
}
}
printArray(task, newtask,qarray);
return 0;
}
In short I'm tottaly stucked
Standard library solution (you can replace std::sort with your own sort function):
#include <iostream>
#include <vector>
#include <algorithm>
struct Team
{
std::uint32_t number;
std::uint32_t quantity;
std::uint32_t penalty;
bool operator < (const Team& other) const
{
bool isEqQuantity = quantity == other.quantity;
bool isEqPenalty = penalty == other.penalty;
return quantity > other.quantity
|| (isEqQuantity && penalty < other.penalty)
|| (isEqQuantity && isEqPenalty && number < other.number);
}
};
int main()
{
std::vector<Team> teams;
//Read teams from file
//....
//Or use other sort
std::sort(teams.begin(), teams.end(), [](const Team& t1, const Team& t2)
{
return t1 < t2;
});
for (auto& t : teams)
{
std::cout << t.number << " ";
}
return 0;
}
Related
PROBLEM STATEMENT
You are given a strictly increasing sequence of integers A1,A2,…,AN. Your task is to compress this sequence.
The compressed form of this sequence is a sequence of ranges separated by commas (characters ','). A range is either an integer or a pair of integers separated by three dots (the string "..."). When each range a...b in the compressed form is decompressed into the subsequence (a,a+1,…,b), we should obtain the (comma-separated) sequence A again.
For each maximal contiguous subsequence (a,a+1,…,b) of A such that b≥a+2, the compressed form of A must contain the range a...b; if b≤a+1, such a sequence should not be compressed into a range. A contiguous subsequence is maximal if it cannot be extended by at least one element of A next to it. It can be proved that the compressed form of any sequence is unique (i.e. well-defined).
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 line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
Output
For each test case, print a single line containing one string ― the compressed form of the given sequence.
Constraints
1≤T≤100
1≤N≤100
1 ≤ Ai ≤ 1000 for each valid i
A1 < A2 < …... <AN
Subtasks
Subtask #1 (100 points): Original constraints
Example Input
3
12
1 2 3 5 6 8 9 10 11 12 15 17
4
4 5 7 8
1
4
Example Output
1...3,5,6,8...12,15,17
4,5,7,8
4
MY Code:
#include <bits/stdc++.h>
using namespace std;
bool b[1005];
int a[1005];
int main()
{
int test, i, j, size, count;
cin >> test;
while (test--)
{
for (i = 0; i < 1005; i++)
b[i] = false;
cin >> size;
for (i = 0; i < size; i++)
{
cin >> a[i];
b[a[i]] = true;
}
for (i = 0; i < 1005; i++)
{
if (b[i] == true)
{
cout << i;
j = i;
count = 0;
while (b[j] == true)
{
count++;
j++;
}
if (count > 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "..." << i - 1 << ",";
else
cout << "..." << i - 1;
}
if (count == 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "," << i - 1 << ",";
else
cout << "," << i - 1;
}
if (count == 1 && ((j - 1) != a[size - 1]))
cout << ",";
}
}
}
return 0;
}
}
MY Question:
Above code runs perfectly on my device giving desired output. But when I am submitting this solution to
Online Judge , it says segmentation fault. It's sure that fundamentally I am accessing the memory incorrectly. Could you please show me where it is?
b is defined a bool[1005]
In this part
for(i=0 ; i<4000 ; i++)
b[i] = false;
You are writing false value 4000 times, exceeding the array size.
Overwriting past the array is allowed on the compiler but will have undefined behaviour in runtime.
In short: it can or can not cause a segfault.
Here is another approach given that the input data is in a file input.txt:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
class Reader {
public:
Reader(const std::string& filename) :
filename_(std::move(filename)), is_(filename_)
{
is_.exceptions( std::ifstream::failbit | std::ifstream::badbit );
}
int get_N() {
int N;
is_ >> N;
return N;
}
std::vector<int> get_ints(int N) {
std::vector<int> v;
v.reserve(N);
for (int i = 0; i < N; i++ ) {
int value;
is_ >> value;
v.push_back(value);
}
return v;
}
int get_num_cases() {
int num_cases;
is_ >> num_cases;
return num_cases;
}
private:
std::string filename_;
std::ifstream is_;
};
bool start_range_cur( std::vector<int> &v, int j, int N )
{
if ( j>= (N - 2) ) return false;
return ((v[j+1] - v[j]) == 1) && ((v[j+2] - v[j+1]) == 1);
}
bool in_range_cur( std::vector<int> &v, int j )
{
return (v[j+1] - v[j]) == 1;
}
void print_range( int min, int max, bool print_comma)
{
std::cout << min << ".." << max;
if (print_comma) std::cout << ",";
}
void print_single(int val, bool print_comma)
{
std::cout << val;
if (print_comma) {
std::cout << ",";
}
}
int main() {
Reader is {"input.txt"};
int num_cases = is.get_num_cases();
for (int i = 0; i < num_cases; i++) {
int N = is.get_N();
std::vector<int> v = is.get_ints(N);
bool in_range = false;
int range_start;
for( int j = 0; j< N; j++ ) {
if (in_range) {
if (j == (N - 1)) {
print_range(range_start, v[j], false);
}
else if (in_range_cur(v, j)) {
continue;
}
else {
print_range(range_start, v[j], true);
in_range = false;
}
}
else {
if (j == (N - 1)) {
print_single(v[j], false);
}
else if (start_range_cur(v, j, N)) {
in_range = true;
range_start = v[j];
}
else {
print_single(v[j], true);
}
}
}
std::cout << '\n';
}
return 0;
}
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'm trying to get the longest(largest) sequence of consecutive prime numbers from an array..
On first test with 10 elements in the array works , but when i tried with 15 elements like: 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 it spit out 4, which is incorrect.
#include <iostream>
using namespace std;
int main()
{
int bar[100];
int x, j = 0;
int maxseq = 0;
int longestseqstart = 0;
cout << "How big is the array? =";
cin >> x;
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
for (int i = 1; i < x - 1; i = j) {
int startseq = i;
int seq = 0;
j = i + 1;
bool prim = true;
int a = bar[i];
for (int d = 2; d <= a / 2; d++) {
if (a % d == 0) {
prim = false;
}
}
while (j < x && prim) {
seq++;
if (seq > maxseq) {
maxseq = seq;
longestseqstart = i;
}
int a = bar[j];
for (int d = 2; d <= a / 2; d++) {
if (a % d == 0) {
prim = false;
}
}
j++;
}
}
cout << "The longest sequence is: ";
cout << maxseq;
return 0;
}
I would write the program the following way
#include <iostream>
#include <iterator>
#include <algorithm>
bool is_prime( unsigned int n )
{
bool prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
int main()
{
unsigned int a[] = { 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t maxseq = 0;
for ( auto current = std::find_if( a, a + N, is_prime );
current != a + N;
current = std::find_if( current, a + N, is_prime ) )
{
auto first = current;
current = std::find_if_not( current, a + N, is_prime );
size_t n = std::distance( first, current );
if ( maxseq < n ) maxseq = n;
}
std::cout << "The longest sequence is: " << maxseq << '\n';
return 0;
}
The program output is
The longest sequence is: 5
I did not use generic functions std::begin( a ) and std::end( a ) because in your program the array can contain less actual elements than the array dimension.
If you do not know yet standard C++ algorithms then the program can be defined the following way
#include <iostream>
bool is_prime( unsigned int n )
{
bool prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
int main()
{
unsigned int a[] = { 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t maxseq = 0;
size_t n = 0;
for ( size_t i = 0; i < N; i++ )
{
bool prime = a[i] % 2 == 0 ? a[i] == 2 : a[i] != 1;
for ( unsigned int j = 3; prime && j <= a[i] / j; j += 2 )
{
prime = a[i] % j != 0;
}
if ( prime )
{
if ( maxseq < ++n ) maxseq = n;
}
else
{
n = 0;
}
}
std::cout << "The longest sequence is: " << maxseq << '\n';
return 0;
}
The program output is the same as above
The longest sequence is: 5
As for your program then this loop
for (int i = 1; i < x - 1; i = j) {
skips the first element of the array that is bar[0].
And due to this statement
j = i + 1;
the calculated value of seq one less than it should be because you do not take into account that bar[i] is already prime.
Set initially seq equal to 1.
int seq = 1;
Moreover you incorrectly are determining prime numbers. For example according to your algorithm 1 is prime.
You are checking twice for prime numbers and you are using a nested loop. That's not necessary. It's enough to read all numbers, check each number, increment the count if it's a prime number and store the maximum sequence length.
#include <iostream>
#include <vector>
using namespace std;
bool isPrime(int a) {
bool prim = true;
for (int d = 2; d*d <= a; ++d) {
if (a % d == 0) {
prim = false;
}
}
return prim;
}
int main()
{
int x;
int longestseqstart = 0;
cout << "How big is the array? =";
cin >> x;
std::vector<int> bar(x);
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
unsigned int count = 0;
unsigned int maxseq = 0;
for (const auto &el : bar) {
if (isPrime(el)) {
++count;
if (count > maxseq) maxseq = count;
} else count = 0;
}
cout << "The longest sequence is: ";
cout << maxseq;
return 0;
}
Of course you can avoid the usage of std::vector and functions with
#include <iostream>
using namespace std;
int main()
{
int x;
int longestseqstart = 0;
cout << "How big is the array? =";
cin >> x;
int bar[100];
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
unsigned int count = 0;
unsigned int maxseq = 0;
for (unsigned int i = 0; i < x; ++i) {
int a = bar[i];
bool prim = true;
for (int d = 2; d*d <= a; ++d) {
if (a % d == 0) {
prim = false;
}
}
if (prim) {
++count;
if (count > maxseq) maxseq = count;
} else count = 0;
}
cout << "The longest sequence is: ";
cout << maxseq;
return 0;
}
The algorithm looks basically OK. The issue is mostly one of organization: the way the inner loop block is set up means that a run of primes will be short by 1 because the longest sequence is only updated at the beginning of the inner loop, missing the final prime.
A couple of minimal failing examples are:
How big is the array? =1
bar[0]=13
The longest sequence is: 0
How big is the array? =2
bar[0]=5
bar[1]=6
The longest sequence is: 0
Note that there's a repeated prime check in two places. This should not be. If we move all of the prime logic into the loop and test for a new longest sequence only after finishing the entire run, we'll have a clear, accurate algorithm:
#include <iostream>
int is_prime(int n) {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int nums[100];
int n;
std::cout << "How big is the array? =";
std::cin >> n;
for (int i = 0; i < n; i++) {
std::cout << "nums[" << i << "]=";
std::cin >> nums[i];
}
int longest = 0;
for (int i = 0, start = 0; i < n; i++) {
for (start = i; i < n && is_prime(nums[i]); i++);
longest = std::max(longest, i - start);
}
std::cout << "The longest sequence is: " << longest;
return 0;
}
In this rewrite I...
avoided using namespace std;.
removed unnecessary/confusing variables.
used clear variable names (bar should only be used in example code when the name doesn't matter).
moved is_prime to its own function.
But there are outstanding issues with this code. It should...
use a vector instead of an array. As it stands, it's vulnerable to a buffer overflow attack should the user specify an array length > 100.
use a faster method of finding primes. We only need to check up to the square root of the number and can skip a lot of numbers such as even numbers after 2. I suspect this is incidental to this exercise but it's worth mentioning.
move the longest_prime_sequence to a separate function (and possibly user input gathering as well).
Convert the array to a Boolean array and find longest length. Try this snippet(not optimized):
bool is_prime(int n) {
for (int i = 2; i < n; i++) {
if (n%i == 0) return false;
}
return true;
}
int main() {
//Input
unsigned int bar[15] = { 3, 5, 7, 8, 9, 11, 13, 17, 19, 20, 23, 29, 31, 37, 41 };
// Convert input to boolean array
bool boo[15];
for (int i = 0; i < 15; i++) {
boo[i] = is_prime(bar[i]);
}
//Check the longest boolean array
int longest = 0;
for (int i = 0; i < 15; i++) {
int count = 0;
while (boo[i + count] && (i+ count) <15) {
count++;
}
if (longest < count) longest = count;
}
//Output
cout << longest;
return 0;
}
Homework: I'm just stumped as hell. I have algorithms set up, but I have no idea how to code this
Just to be clear you do not need arrays or to pass variables by reference.
The purpose of the project is to take a problem apart and using Top-Down_Design or scratch pad method develop the algorithm.
Problem:
Examine the numbers from 2 to 10000. Output the number if it is a Dual_Prime.
I will call a DualPrime a number that is the product of two primes. Ad where the two primes are not equal . So 9 is not a dual prime. 15 is ( 3 * 5 ) .
The output has 10 numbers on each line.
My Algorithm set-up
Step 1: find prime numbers.:
bool Prime_Number(int number)
{
for (int i = 2; i <= sqrt(number); i++)
{
if (number % 1 == 0)
return false;
}
return true;
}
Step 2: store prime numbers in a array
Step 3: Multiply each array to each other
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int j = 0; j < Size- 1; j++)
{
Dual_Prime[] = Arr[j] * Arr[j + 1]
}
}
Step 4: Bubble sort
void Bubble_Sort(int Array[], int Size) // Sends largest number to the right
{
for (int i = Size - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (Array[j] > Array[j + 1])
{
int Temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = Temp;
}
}
Step 5: Display New Array by rows of 10
void Print_Array(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
cout << Dual_Prime[i] << (((j % 10) == 9) ? '\n' : '\t');
}
cout << endl;
}
I haven't learned dynamic arrays yet,
Although dynamic arrays and the sieve of Eratosthenes are more preferable, I tried to write minimally fixed version of your code.
First, we define following global variables which are used in your original implementation of Multiply_Prime_Numbers.
(Please check this post.)
constexpr int DP_Size_Max = 10000;
int DP_Size = 0;
int Dual_Prime[DP_Size_Max];
Next we fix Prime_Number as follows.
The condition number%1==0 in the original code is not appropriate:
bool Prime_Number(int number)
{
if(number<=1){
return false;
}
for (int i = 2; i*i <= number; i++)
{
if (number % i == 0)
return false;
}
return true;
}
In addition, Multiply_Prime_Numbers should be implemented by double for-loops as follows:
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int i = 0; i < Size; ++i)
{
for (int j = i+1; j < Size; ++j)
{
Dual_Prime[DP_Size] = Array[i]*Array[j];
if(Dual_Prime[DP_Size] >= DP_Size_Max){
return;
}
++DP_Size;
}
}
}
Then these functions work as follows.
Here's a DEMO of this minimally fixed version.
int main()
{
int prime_numbers[DP_Size_Max];
int size = 0;
for(int j=2; j<DP_Size_Max; ++j)
{
if(Prime_Number(j)){
prime_numbers[size]=j;
++size;
}
}
Multiply_Prime_Numbers(prime_numbers, size);
Bubble_Sort(Dual_Prime, DP_Size);
for(int i=0; i<DP_Size;++i){
std::cout << Dual_Prime[i] << (((i % 10) == 9) ? '\n' : '\t');;
}
std::cout << std::endl;
return 0;
}
The Sieve of Eratosthenes is a known algorithm which speeds up the search of all the primes up to a certain number.
The OP can use it to implement the first steps of their implementation, but they can also adapt it to avoid the sorting step.
Given the list of all primes (up to half the maximum number to examine):
Create an array of bool as big as the range of numbers to be examined.
Multiply each distinct couple of primes, using two nested loops.
If the product is less than 10000 (the maximum) set the corrisponding element of the array to true. Otherwise break out the inner loop.
Once finished, traverse the array and if the value is true, print the corresponding index.
Here there's a proof of concept (implemented without the OP's assignment restrictions).
// Ex10_TwoPrimes.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Homework_Header(string Title);
void Do_Exercise();
void Sieve_Of_Eratosthenes(int n);
void Generate_Semi_Prime();
bool Semi_Prime(int candidate);
bool prime[5000 + 1];
int main()
{
Do_Exercise();
cin.get();
return 0;
}
void Do_Exercise()
{
int n = 5000;
Sieve_Of_Eratosthenes(n);
cout << endl;
Generate_Semi_Prime();
}
void Sieve_Of_Eratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool Semi_Prime(int candidate)
{
for (int index = 2; index <= candidate / 2; index++)
{
if (prime[index])
{
if (candidate % index == 0)
{
int q = candidate / index;
if (prime[q] && q != index)
return true;
}
}
}
return false;
}
void Generate_Semi_Prime()
{
for (int i = 2; i <= 10000; i++)
if (Semi_Prime(i)) cout << i << "\t";
}
I have the folowing problem:
Farmer John has built a new long barn, with N (2 <= N <= 100,000)
stalls. The stalls are located along a straight line at positions
x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become
aggressive towards each other once put into a stall. To prevent the
cows from hurting each other, FJ wants to assign the cows to the
stalls, such that the minimum distance between any two of them is as
large as possible. What is the largest minimum distance?
Input
t – the number of test cases, then t test cases follows.
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
For each test case output one integer: the largest minimum distance.
Example
Input:
1
5 3
1
2
8
4
9
Output:
3 Output details:
FJ can put his 3 cows in the stalls at positions 1, 4 and 8,
resulting in a minimum distance of 3. Submit solution!
My approach was to pick some pair which has a certain gap and check if there are enough elements in the array to satisfy the need of all the cows.
To find these elements,I used binary search.
When I find an element , I reset my left to mid so I can continue based on the number of cows left.
My code:
#include <iostream>
int bsearch(int arr[],int l,int r,int gap , int n,int c){
int stat = 0;
for (int i = 1;i <= c; ++i) {
while(l <= r) {
int mid = (l+r)/2;
int x = n+(i*gap);
if (arr[mid] > x && arr[mid-1] < x) {
l = mid;
++stat;
break;
}
if(arr[mid] < x) {
l = mid + 1;
}
if (arr[mid] > x) {
r = mid - 1;
}
}
}
if (stat == c) {
return 0;
}
else {
return -1;
}
}
int calc(int arr[],int n , int c) {
int max = 0;
for (int i = 0; i < n; ++i) {
for (int j = i+1;j < n; ++j) {
int gap = arr[j] - arr[i];
if (gap > max) {
if (bsearch(arr,j,n-1,gap,arr[j],c) == 0) {
max = gap;
}
}
}
}
return max;
}
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t , n ,c;
cin >> t;
for(int i = 0 ; i < t; ++i) {
cin >> n >> c;
int arr[n];
for (int z = 0 ; z < n; ++z) {
cin >> arr[z];
}
sort(arr,arr+n);
//Output;
int ans = calc(arr,n,c);
cout << ans;
}
return 0;
}
Problem Page:
https://www.spoj.com/problems/AGGRCOW/