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
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <unordered_map>
using namespace std;
#define VAR(n,v) typeof(v) n=(v)
#define REP(i,n) for(int i=1; i<=(n); ++i)
#define FOR(i,a,b) for(VAR(i,a); i!=(b); ++i)
#define FORE(it,t) FOR(it,t.begin(),t.end())
typedef vector<int> vi;
#define pb push_back
typedef unordered_map<int,int> hii;
typedef pair<int,int> pii;
#define mp make_pair
#define st first
#define nd second
typedef long long ll;
#define INF 1000000001
#define sz size()
#define ALL(t) (t).begin(),(t).end()
#define SC(a) scanf("%d", &a)
#define GET(a) int a; SC(a)
#define ISDEBUG 0
#define dprintf(...) if(ISDEBUG) \
	{printf("\033[31m"); printf(__VA_ARGS__); printf("\033[0m");}
template <class It> void dptab(It b, It e, const char* f="%d ")
	{if(ISDEBUG) {for(It it=b; it!=e; ++it) dprintf(f, *it); dprintf("\n"); }}

int n;

struct query {
	int i,j,c;
	bool operator<(const query& q) const {
		return c < q.c;
	}
};

vector<query> queries;

hii b2e, e2b;

void insert(int i, int j) {
	b2e[i] = j;
	e2b[j] = i;
}

void remove(int i, int j) {
	b2e.erase(i);
	e2b.erase(j);
}

bool add(int i, int j) {
	if(i==j) return false;

	if(b2e.count(i)) {
		int mn = min(b2e[i], j);
		int mx = max(b2e[i], j);
		remove(i, b2e[i]);
		insert(i, mn);
		return add(mn, mx);
	}
	else if(e2b.count(j)) {
		int mn = min(e2b[j], i);
		int mx = max(e2b[j], i);
		remove(e2b[j], j);
		insert(mx, j);
		return add(mn, mx);
	}
	else {
		insert(i, j);
		return true;
	}
}

int main() {
	SC(n);
	REP(i, n) FOR(j,i,n+1) {
		GET(c);
		queries.pb({i,j+1,c});
	}
	sort(ALL(queries));

	int cost = 0;
	for(query& q: queries) {
		if(!n) break;
		if(add(q.i, q.j)) {
			--n;
			cost += q.c;
			dprintf("used query\t%d-%d: %d\n", q.i, q.j-1, q.c);
		}
		else 
			dprintf("refused\t%d-%d: %d\n", q.i, q.j-1, q.c);
		for(auto kv: b2e)
				dprintf("[%d,%d) ", kv.st, kv.nd);
			dprintf("\n");
	}
	printf("%d\n", cost);
}