#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define pb push_back
#define mp make_pair
#define fast ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
#define ff first
#define ss second
#define INF (ll) 1e9
#define endl "\n"
#define tt ll testcase; cin>>testcase; while(testcase--)
 
int main(){
	fast;
	ll n;
	cin>>n;
	vector <pair <ll, ll>> a;
	pair<ll ,ll> p;
	ll t;
	p = {0,0};
	a.pb(p);
	for(ll i=1; i<=n; i++){
		cin>>t;
		p = mp(t, i);
		a.pb(p);
	}
	sort(a.begin()+1, a.end());
	ll ans=0;
	ll dp[n+1][n+1]={};
	for(ll len = n; len>=1; len--){
		for(ll st=1; st <= n-len+1; st++){
			if(len==1){
				ans = max(ans, dp[st][st] + a[len].ff*abs(a[len].ss - st));
			}
			else{
				dp[st+1][st + len - 1] = max(dp[st+1][st+len-1], dp[st][st+len-1] + a[len].ff*abs(a[len].ss - st));
				dp[st][st + len - 2] = max(dp[st][st + len-2], dp[st][st+len-1] + a[len].ff*abs(a[len].ss-(st+len-1)));

			}
		}
	}
	cout<<ans<<endl;
	for(ll i=1; i<=n; i++){
		for(ll j=1; j<=n; j++){
			cout<<dp[i][j]<<" ";
		}
		cout<<endl;
	}
}