Help me pls

given a 2d array NxN. You can get N^2 values by adding elements from each row. Find the smallest N of these sums. you are allowed to use only one element from the row each time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 #include <bits/stdc++.h> 
#include <iostream>
using namespace std;
int main(){
    long n;
    cin>> n;
    long a[n][n] , d[n], r[n];
    long s = 0;
    long mins = 0;
    for(int i = 0 ; i < n ; i++){
        for(int j = 0 ; j < n ; j++){
            cin>>a[i][j];
        }
    }
    for(int i = 0 ; i < n ; i++){
        sort(a[i], a[i] + n);
    }
    for(int i = 0 ; i < n ; i++){
        d[i] = a[i][1] - a[i][0];
    }int k = sizeof(d)/sizeof(d[0]);
    sort(d, d + k);
    for(int i = 0 ; i < n ; i++){
        mins = mins + a[i][0];
    }r[0] = mins;
    for(int i = 1 ; i < n ; i++){
        r[i]= mins + d[i-1];
    }
    for(int i = 0 ; i < n ; i++){
        cout<<r[i]<<' ';
    }
    return 0;

}
    what do I need to improve or use?
Last edited on
You can't declare 2D array parameter like that. Arrays in C is broken, and that's been passed to C++.

Further more, you want to set the array size at runtime, which means you need to allocate the memory somehow. That declaration of a isn't allowed in C++, and shouldn't have been added to C99.

The C++ standard template library has a number of containers, and although there isn't a 2D array type, there's something that can help. Are you allowed to use STL in your program?
long may be same as int.
computing the size of an array that you already should have known the size of adds obscure pointer code for no reason. Pass in the size, keep track of it, don't recompute it.
x = x+y should just be written x+= y; its not wrong, its just bloated visually.

unless you are writing a low budget book, jamming all the code together with no whitespace and no comments is of no value. comment what things do. Use variable names that imply what stuff is. Name your functions something meaningful, rather than func().

compile this with errors and warnings turned on and language extensions turned off. As noted you use a bunch of language extensions which is fine in small programs if you understand the problems, but its not fine in quality c++ code because it won't work on all compilers and may even break in new versions of same compiler. You don't include anything to pick up sort; you just trust that its going to be there (and the compiler filled in for you) .. include the includes that hold the tools you use.


sorry i submitted
the wrong code
Topic archived. No new replies allowed.