#include<cstdio>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
set<int> en[2004];
set<int> be[2004];
bool tt[2004][2004];
void add(int i, int j) {
set<int>::iterator it;
if (tt[i][j]) {
return;
}
tt[i][j] = true;
for(it = en[j].begin(); it != en[j].end(); ++it) {
en[i].insert(*it);
be[*it].insert(i);
}
for(it = be[i].begin(); it != be[i].end(); ++it) {
be[j].insert(*it);
en[*it].insert(j);
}
for(it = en[i].begin(); it != en[i].end(); ++it) {
add(*it + 1, j);
}
for(it = be[j].begin(); it != be[j].end(); ++i) {
add(i, *it - 1);
}
}
bool check(pair<int, int> p) {
if (en[p.first].find(p.second) != en[p.first].end()) {
return false;
}
add(p.first, p.second);
return true;
}
int main() {
int n; scanf("%d", &n);
vector<pair<int, pair<int, int> > > vp;
for(int i = 0; i < n; ++i) {
for(int j = i; j < n; ++j) {
int d; scanf("%d",&d);
vp.push_back(make_pair(d, make_pair(i, j)));
}
}
sort(vp.begin(), vp.end());
int ile = 0, i = 0;
long long c = 0;
while (ile < n) {
pair<int, pair<int, int> > p = vp[i];
if (check(p.second)) {
ile++;
c += p.first;
}
i++;
}
printf("%lld\n", c);
}
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 | #include<cstdio> #include<algorithm> #include<set> #include<vector> using namespace std; set<int> en[2004]; set<int> be[2004]; bool tt[2004][2004]; void add(int i, int j) { set<int>::iterator it; if (tt[i][j]) { return; } tt[i][j] = true; for(it = en[j].begin(); it != en[j].end(); ++it) { en[i].insert(*it); be[*it].insert(i); } for(it = be[i].begin(); it != be[i].end(); ++it) { be[j].insert(*it); en[*it].insert(j); } for(it = en[i].begin(); it != en[i].end(); ++it) { add(*it + 1, j); } for(it = be[j].begin(); it != be[j].end(); ++i) { add(i, *it - 1); } } bool check(pair<int, int> p) { if (en[p.first].find(p.second) != en[p.first].end()) { return false; } add(p.first, p.second); return true; } int main() { int n; scanf("%d", &n); vector<pair<int, pair<int, int> > > vp; for(int i = 0; i < n; ++i) { for(int j = i; j < n; ++j) { int d; scanf("%d",&d); vp.push_back(make_pair(d, make_pair(i, j))); } } sort(vp.begin(), vp.end()); int ile = 0, i = 0; long long c = 0; while (ile < n) { pair<int, pair<int, int> > p = vp[i]; if (check(p.second)) { ile++; c += p.first; } i++; } printf("%lld\n", c); } |
English