This is the problem:
Lili is organizing a competition at her school. There are N × N people in a room-sized N × N and each one of them belongs to a team. The team is numbered between 1 to N. In the room, people wear a shirt with numbers between 0 to N indicating team number they come from. People that wears number 0 is spectator.
Lili wants to know whether each team consists of at least N members and are in the room. Help Lili to count how many incomplete teams in the room.
Input:
Input consists of one integer N , number of team participating in this competition followed by N lines consisting of N integers Aij with value between 0 and N inclusive, each representing the numbers in the people’s shirts.
Constraints:
1 ≤ N ≤ 100
Output:
Output the number of incomplete teams in the room.
Sample input 1:
2
1 0
2 2
Output 1:
1
Sample input 2:
3
3 0 2
2 0 2
1 3 3
Output 2:
1
This is my current code but it keeps saying wrong answer
#include <stdio.h>
int main() {
int n, array[101][101], i, j, count = 0, k, x = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &array[i][j]);
}
}
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (array[i][j] == k + 1) {
count += 1;
}
}
}
if (count != n) {
x += 1;
}
count = 0;
}
printf("%d\n", x);
return 0;
}
First of all you do not need a 2D array of size NxN, but a single 1D array of size N (or just N-1) to count how many people are in each team.
And as you need a dynamic size array (N is only known at run time), you can simply use an allocated array of integers. Because I would bet a coin that you problem comes when N > 101...
Algo in pseudo-code:
read N
alloc an array teams of size N-1 and initialize it with 0
loop N * N times
| read a shirt number i
| if i > 0
| | increase teams[i - 1]
let incomplete be a 0 value integer
loop N-1 times
| if teams[i] < N
| | increase incomplete
output incomplete
At first glance your solution seems correct excepting for two flaws:
count != n expression should be count < n
It might be too slow. #Serge Ballesta solution is O(N^2) but yours is O(N^3)
a 101x101 array is big enough, you could even use a 100x100 array instead. You can also allocate a NxN array using malloc, which would make your code more flexible but also a bit more complex.
Although StackOverflow is not the right site for this question, here we go. The mistake lies here:
if (count != n) {
x += 1;
}
The problem statement mentioned that the size of the incomplete team is less than N. Change the sign != to <, and the algorithm is correct. But, It may not be accepted by the online judge since it can be optimized further. Here's the optimized version:
#include <stdio.h>
int main() {
int N;
scanf("%d", &N);
/**
* arr[i] stores the size of (i + 1)th team.
* it's not necessary to store the spectator's count.
*/
int arr[N];
for (int i = 0; i < N; i++) {
arr[i] = 0;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int team;
scanf("%d", &team);
if (team > 0) {
/* incrementing the size of team */
arr[team - 1]++;
}
}
}
int incomplete_teams = 0;
for (int i = 0; i < N; i++) {
if (arr[i] < N) {
incomplete_teams++;
}
}
printf("%d\n", incomplete_teams);
return 0;
}
Related
/*
The program must accept N integers as the input. Each integer is
given a weight. The program must sort the integers in ascending
order based on their weight and print the integers along with their
weights as the output as given in the Example Input/Output
sections. The weight of each integer is calculated based on the
conditions given below.
Conditions:
Weight = 5 if it is a perfect cube.
Weight = 4 if it is a multiple of 4 and divisible by 6.
Weight = 3 if it is a prime number.
Hint: Use stable sort (insertion sort, bubble sort or merge sort).
Boundary Conditions:
1 <= N <= 1000
Input Format:
The first line contains N.
The second line contains N integers separated by a space.
Output Format:
The first line contains integers with their weight as given in the Example Input/Output sections.
Example Input/Output 1:
Input:
7
10 36 54 89 12 216 27
Output:
<10,0>,<54,0>,<89,3>,<36,4>,<12,4>,<27,5>,<216,9>
Example Input/Output 2:
Input:
10
12 18 16 64 14 30 37 27 343 216
Output:
<18,0>,<16,0>,<14,0>,<30,0>,<37,3>,<12,4>,<64,5>,<27,5>,<343,5>,<216,9>
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int perfcube(int n)
{
int cubert = cbrt(n);
if (cubert * cubert * cubert == n)
{
return 1;
}
else
return 0;
}
int divis(int n)
{
if (n % 4 == 0 && n % 6 == 0)
{
return 1;
}
return 0;
}
int prime(int n)
{
int count = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
count++;
}
}
if (count == 2)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int n;
scanf("%d", &n);
int a[n];
int b[n][2];
// scanning n variables into array a
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// copying rows of a(1d array) to b(2d array)
int l = 0; // variable to traverse 1d array without its own loop
// traverse 2d array
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 2; k++)
{
if (k == 0)
{
// if k = 0 that is first col then store 1st col value of 1d array to 2d array
b[j][k] = a[l++];
}
else
{
// if other cols come then skip it
continue;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
if (j == 0)
{
if (perfcube(b[i][j]))
{
b[i][j + 1] += 5;
}
if (divis(b[i][j]))
{
b[i][j + 1] += 4;
}
if (prime(b[i][j]))
{
b[i][j + 1] += 3;
}
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
printf("<%d,>", b[i][j]);
}
printf("\n");
}
return (0);
}
I tried approaching the problem like this and ended up with an output like this. Please help me proceed from here.
Output
<10,><0,>
<36,><4,>
<54,><0,>
<89,><3,>
<12,><4,>
<216,><9,>
<27,><5,>
I am new to programming
I have tried approaching the problem like this and ended up with an output like that.
Please help me proceed from here.
I am not allowed to use pointers or functions like qsort
How do I sort these in that format and print it
Output of the program that I ended up with.
The output should match the question.
Sorting, at its core, centers around the comparison of two items. For example, if A < B, then A should come before B.
For example, we can reorder
3 5 2 1 4
to
1 2 3 4 5
We can see it is correct because each adjacent pair maintains a ≤ relationship.
This relationship is a comparison function. The one used for your standard sorting looks something like this:
bool compare( int a, int b )
{
return a <= b;
}
What your homework is asking you to do is change the comparison function to not compare the values directly, but compare the results of a function applied to them:
bool compare( int a, int b )
{
return weight_function( a ) <= weight_function( b );
}
You must write and implement the weight function, then use it in your sorting algorithm.
(Your algorithm probably has an if (a <= b) in it somewhere, which you could rewrite as if (compare( a, b ))... but you don’t need to do that, just use the weight functions properly.
I have puzzles that looks like this:
=== ====
=== ===
=== ====
left edge has length from 0 to 10 000 and right also, middle part is from 1 to 10 000.
So the question is if i can build a rectangle? like first puzzle has length of left edge equal to 0 and the last puzzle has right edge of length 0 and in the middle they fit perfectly?
I am given the number of puzzle i have and their params like this:
6
1 9 2
0 3 1
0 4 1
8 9 0
2 9 0
1 5 0
and result can be any of that:
2
0 3 1
1 5 0
or
3
0 3 1
1 9 2
2 9 0
or
2
0 4 1
1 5 0
But if there is no result i have to printf("no result")
I have to do this in C, I thought about doing some tree and searching it with BFS where vertices would have edge lengths and edge would have middle length and when reached 0 i would go all way up and collect numbers but it's hard to code. So i decided to do recursion but im also stuck:
#include<stdio.h>
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int tab[a][3];//array for puzzles
int result[][3];//result array
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
int findx(int x, int a, int *tab[], int *result[], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[a][0] == x){//there i look for puzzles with x length at start
if(tab[a][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[a][m];
}
return print_result(result, k);//we will return result go to print_result function
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[a][m];
k += 1;
}
findx(tab[a][2], a, tab, result, k);
}
}
}
printf("no result");
}
int print_result(int *result[], int k){
printf("%d", &k);//how many puzzles i have
printf("\n");
for(int i = 0; i < k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", &result[i][j]);
}
printf("\n");//...in separate lines
}
}
I have an error that result array can't look like this int result[][3] because of of [] but I don't know how many puzzles I'm gonna use so?... and I have implicit declaration for both of my functions. Guys please help, I dont know much about C and its super hard to solve this problem.
I'm not sure I understand the overall logic of the problem, but you definitely are in need of some variable sized containers for result AND tab. Arrays are fixed size and must be defined at compile time. The following should at least compile without warnings:
#include<stdio.h>
#include<stdlib.h>
void print_result(int (*result)[3], int k){
printf("%d", k);//how many puzzles i have
printf("\n");
for(int i = 0; i <= k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", result[i][j]);
}
printf("\n");//...in separate lines
}
}
void findx(int x, int a, int (*tab)[3], int (*result)[3], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[i][0] == x){//there i look for puzzles with x length at start
if(tab[i][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[i][m];
}
print_result(result, k);//we will return result go to print_result function
return;
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[i][m];
k += 1;
///** Increase size of result **/
//int (*newptr)[3] = realloc(result, (k+1) * sizeof(int[3]));
//if (newptr)
// result = newptr;
}
findx(tab[i][2], a, tab, result, k);
}
}
}
printf("no result\n");
}
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int (*tab)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int (*result)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
Note that I changed the tab and result types to (*int)[3]. Due to order of operations, we need parentheses here. Because they are variable size, they require dynamic memory allocations. In the interest of brevity and readability, I did not check the returned values of malloc or realloc. In practice, you should be checking that the returned pointer is not NULL. Because we are using dynamic memory allocations, we should also use free if you plan on doing anything else with this program. Otherwise, it doesn't really matter because exiting the program will free the resources anyway. You actually don't want to free. because we are passing a pointer by value to findx and the realloc can change the address, it may come back with a different address. Also, take note that I needed to include <stdlib.h> for the dynamic memory allocations.
Additional Issues
Your functions print_results and findx are not declared when you call them in main. Your function either need to be above main or have "function prototypes" above main.
In the printfs you do not need the &. You do not want to send the address of the variable to printf. You want to send what will actually be printed.
Now what?
The program still does not provide you with the correct results. It simply outputs 0 as the result every time. This should at least give you a starting point. By changing this line in print_results:
for(int i = 0; i < k; i++){//printing puzzles...
to
for(int i = 0; i <= k; i++){//printing puzzles...
I was at least able to output 0 0 0. This seems more correct because if k is 0, we don't loop at all.
#include<stdio.h>
void findx(int x, int a, int tab[a][3], int result[200000][3], int puzzlesinresult) { //i am looking for puzzle with length x on start
for (int i = 0; i < a; i++) {
if (tab[i][0] == x) { //there i look for puzzles with x length at start
if (tab[i][2] == 0) { //if i find such puzzle i check if this is puzzle with edge length zero at the end
for (int m = 0; m < 3; m++) { //this for loop add to my result array last puzzle
result[puzzlesinresult][m] = tab[i][m];
}
return print_result(result, puzzlesinresult); //we will return result go to print_result function
} else { //if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
while (result[puzzlesinresult - 1][2] != tab[i][0] && puzzlesinresult > 0) {
puzzlesinresult -= 1;
}
int isusedpuzzle = 0;
for (int j = 0; j < puzzlesinresult; j++) {
if (result[j][0] == tab[i][0] && result[j][1] == tab[i][1] && result[j][2] == tab[i][2]) {
isusedpuzzle = 1;
} else {
//pass
}
}
if (isusedpuzzle == 0) {
for (int m = 0; m < 3; m++) {
result[puzzlesinresult][m] = tab[i][m];
}
puzzlesinresult += 1;
findx(tab[i][2], a, tab, result, puzzlesinresult);
}
}
}
}
}
void print_result(int result[200000][3], int puzzlesinresult) {
printf("%d\n", puzzlesinresult + 1); //how many puzzles i have
for (int i = 0; i < puzzlesinresult + 1; i++) { //printing puzzles...
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n"); //...in separate lines
}
exit(0);
}
int main() {
int a;
scanf("%d", & a); //here i get how many puzzles i have
int tab[a][3]; //array for puzzles
int result[100][3]; //result array
int puzzlesinresult = 0; //this will help me track how many puzzles has my result array
for (int i = 0; i < a; i++) { //upload puzzles to array
for (int j = 0; j < 3; j++) {
scanf("%d", & tab[i][j]);
}
}
for (int i = 0; i < a; i++) { //here i delete puzzles that doesnt contribute anything like 1 x 1,2 x 2,..
if (tab[i][0] == tab[i][2] && tab[i][0] != 0) {
for (int p = i; p < a; p++) {
for (int j = 0; j < 3; j++) {
tab[p][j] = tab[p + 1][j];
}
}
}
}
findx(0, a, tab, result, puzzlesinresult); //start of recursion, because start has to be length 0
printf("NONE");
}
This returns sometimes correct result. If you can find when this program fails I would rly appreciate sharing those cases with me :)
in regarding to my previous post: Complexity to find if there is a missing element in an array --> i am trying to solve an algorithm to check if an array has all elements between 0 and n - 1 in the most efficient way (time complexity wise) without an extra array,. i came up with two solutions. could you help me determine which one is more efficient? which one should i turn in? thank you.
/* first attempt */
int check_missing_a(int *a, int n)
{
int i, flag = 0;
for (i = 0; i < n; i++)
{
if (a[i] < 0 || a[i] >= n) //check for unwanted integers
return 0;
while (i != a[i])
{
swap(&a[a[i]], &a[i]); //puts numbers in their index
flag++;
if (flag > 1 && a[i] == a[a[i]]) //check for duplicates
return 0;
}
flag = 0;
}
return 1;
}
/* second attempt */
int check_missing_b(int *a, int n)
{
int i, sum_a = 0, sum_i = 0, sum_aa = 0, sum_ii = 0;
for (i = 0; i < n; i++)
{
if (a[i] < 0 || a[i] >= n) //check for unwanted integers
return 0;
else
{
sum_a += a[i]; // sum of 'elements' should be equal to sum of 'i'
sum_i += i;
sum_aa += a[i] * a[i]; // multiplication sum of 'elements' should be equal to multiplication sum of 'i'
sum_ii += i * i;
}
}
return (sum_aa == sum_ii && sum_a == sum_i);
}
First of all, we need to fix check_missing_a because it's buggy. After the swap, a[i] might be out of bounds for following a[a[i]]. Fixed version:
int check_missing_a2(int *a, int n) {
for (int i = 0; i < n; ++i) {
while (i != a[i]) {
if (a[i] < i || a[i] >= n || a[i] == a[a[i]])
return 0;
swap(&a[i], &a[a[i]]);
}
}
return 1;
}
We can even save a few comparisons as follows: (Thanks to #chmike)
int check_missing_a2(int *a, int n)
{
for (int i = 0; i < n; ++i)
if (a[i] < 0 || a[i] >= n)
return 0;
for (int i = 0; i < n; ++i) {
while (i != a[i]) {
if (a[i] == a[a[i]])
return 0;
swap(&a[i], &a[a[i]]);
}
}
return 1;
}
Complexity of check_missing_a2
At first glance, one might think that check_missing_a2 is slower than O(N) because the outer loop does N passes and there's another inner loop.
However, the inner loop performs at most N-1 swaps. For example, the following illustrates the number of swaps for each arrangement of the numbers in 0..N-1 for N=8:
# swaps # arrangements
------- --------------
0 1
1 28
2 322
3 1960
4 6769
5 13132
6 13068
7 5040
As #4386427 explained, every swap places at least one element in its correct position. Consequently there can't be more than N swaps.
This means that no part of the function is executed more than 2*N times, for a resulting complexity of O(N).
Complexity of check_missing_b
A single loop with N passes, for a complexity of O(N).
As for actual performance, I suspect that check_missing_a2 will always be faster than check_missing_b.
Of course, there's also the issue that check_missing_a2 changes the array and that check_missing_b could overflow.
Function check_missing_b is definitely O(n) because it has only one loop. It also has the property to not modify the input array a. However, it has a limitation in the magnitude of n because sum_ii might overflow.
Function check_missing_a has two loops and is less obvious to analyze. It also sort the values in the array a and thus modify the input array. This might be a problem. On the other hand it is not subject to overflow which is an advantage over the other function.
This function is a radix sort because each swap puts a value in its final place. There will be less than n swaps. This function is thus O(n).
Unfortunately, this function has also a problem. A value a[a[i]] may be bigger than n when a[i] > i. The function requires thus two pass on the elements. A first pass, ensures that no value is smaller than 0 and bigger than n-1. A second pass does the radix sort.
Here is my suggested implementation of the function check_missing_a.
int check_missing_c(int *a, int n)
{
for (int i = 0; i < n; i++)
if (a[i] < 0 || a[i] >= n)
return 0;
for (int i = 0; i < n; i++)
while (i != a[i]) {
if (a[i] == a[a[i]])
return 0;
int tmp = a[i];
a[i] = a[tmp];
a[tmp] = tmp;
}
return 1;
}
The aim of this assignment is to find the number of pairs can be formed by every two number in an array. The condition is that these two number can not have common factors.
I have tried using loop comparing number by number in an array with a loop of factor starts from 2. This code works but it exceeds the time limit for 2 out of 10 cases on codecrunch.
double estimate_PI(int list[], int size) {
int i, pair;
pair = size * (size - 1) / 2; //total number of pairs can be formed
int count = pair;
int j, l;
for (i = 0; i < size; i++) { //check the first number in the array
for (j = i + 1; j < size; j++) { //check compare the first number of the rest
// of the numbers in the array
for (l = 2; l < list[j]; l++) { //check for common factors
if (list[i] % l == 0 && list[j] % l == 0) { //if these two values have common factor
count--; //the possible number of pair reduce by 1
break;
}
}
}
}
// printf("%d\n count",count);
double PI = sqrt(6.0000 * pair / count);
return PI;
}
For this method it takes too long for the codecrunch to run and it mark me wrong.
Rather than try every value [2...list[j]), perhaps look for the Greatest common divisor
Example int gcd(int a, int b) Arjun Sreedharan or chux
#if 0
for (l = 2; l < list[j]; l++) { //check for common factors
...
}
#else
if (gcd(list[i], list[j]) <= 1) count--;
#endif
Simplification possible as only the first factor > 1 needs to be found.
I do a code that will display to the screen 10 random numbers with no repetitions. I want to know if we can optimize the code or if you have a better and simple way in order to do this request.
Thanks !!
int main(){
int nbr = 0; srand(time(NULL));
int arr[10], i, j, flag;
for (i = 0; i < 10; i++)
{
do
{
nbr = rand() % 10 + 1;
flag = 1;
for (j = 0; j < i; j ++)
{
if (nbr == arr[j])
{
flag = 0;
break;
}
}
} while (!flag);
arr[i] = nbr;
}
for (i = 0; i < 10; i++)
{
printf("%5d", arr[i]);
}
system("PAUSE");
return 0;
}
So if i get what you're trying to do here it is:
generate an array of numbers between 1 and 10, in a random order (given rand() % 10 + 1)
instead of trial and error I'd suggest the following algorithm:
fill arr with 1...10
shuffle arr
this will run a lot faster
While I agree with the solution provided by Work of Artiz, this will result in the hard question to answer of when to stop shuffling.
To solve this you can use the following solution (which will use more memory, but less clock time):
1 Create an array temp having values 1..10 (ordered, not random)
2 Keep track of the length length of the array (10)
3 Generate a random index rand_i between 0 and length - 1
4 Copy temp[rand_i] to next position in your final array
5 Overwrite temp[rand_i] by temp[length-1]
6 Decrement length
7 Iterate Steps 3 - 6 until your array is filled (10 times)
This will both eliminate your excessive looping, and the problem of when to stop shuffling your array
EDIT: including code
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(){
int nbr = 0; srand(time(NULL));
int arr[10], i, j, flag;
int temp[10] = {1,2,3,4,5,6,7,8,9,10};
int length = 10;
for (i = 0; i < 10; i++)
{
nbr = rand() % length; // Generate random index between 0 and length - 1
arr[i] = temp[nbr]; // Copy value from random index in temp to next index in arr
// Now since temp[nbr] is already taken (copied to arr) we should replace it by last available value in temp (temp[lenght])
// and in the next iteration we will create a value between 0 and length -1. This will keep values not yet taken from temp in
// contiguous order
temp[nbr] = temp[length-1];
length--;
}
for (i = 0; i < 10; i++)
{
printf("%5d", arr[i]);
}
return 0;
}