Matrix: sum of indexes#9893

Matrix: sum of indexes (Editorial)

Solution

General Idea: We need to construct an n \times n matrix where each element m[i][j] = i + j with 1-based indexing. The simplest approach is to iterate over all rows and columns and compute the sum directly. For proper formatting, each number should be printed with a width of 2 characters.

Time complexity: \mathcal{O}(n^2).


#include <bits/stdc++.h>
#define int long long
#define ld long double
#define nl "\n"
#define ull unsigned long long
#define rv return void
#define str string
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define vec vector
#define fixed(n) fixed << setprecision(n)
#define Moageza ios::sync_with_stdio(false);cout.tie(NULL);cin.tie(NULL);
using namespace std;
//////////////////////////////////////////////////////
void solve() {
 int n;cin>>n;
 vec<vec<int>>v(n,vec<int>(n));
 for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
        v[i][j]=i+j+2;
    }
 }
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cout<<v[i][j]<<" ";
        }
        cout<<nl;
    }
}
signed main()
{
    Moageza
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    int t = 1;
    // cin >> t;
    while (t--) {
        solve();
        // cout << nl;
    }
    return 0;
}