Pagini recente » Istoria paginii runda/monthly-2014-runda-3 | Cod sursa (job #1169916) | Cod sursa (job #2859350) | Cod sursa (job #3220984) | Cod sursa (job #1708399)
/*
* main.cpp
*
* Created on: May 24, 2016
* Author: alexei
*/
#include <cstdio>
#include <algorithm>
#include <vector>
#include <limits>
#include <set>
#define NMAX 200020
#define MAX_T 20
#define MAX_N 200000
#define MAX_X 1000000000
class Point {
public:
int x, y;
int idx;
Point(int x, int y): x(x), y(y) {
}
};
// Manhattan distance
inline int distance(Point& p1, Point& p2) {
return std::abs(p1.x - p2.x) + std::abs(p1.y - p2.y);
}
int min_dist[NMAX];
long long brute_prim(std::vector<Point>& points) {
int N = points.size();
long long mst_cost = 0;
// boot-up MST from point 0
min_dist[0] = std::numeric_limits<int>::max();
for (int i = 1; i < N; ++i) {
min_dist[i] = distance(points[i], points[0]);
}
for (int i = 1; i < N; ++i) {
// search for the nearest point in plane
int nearest_neigh_dist = std::numeric_limits<int>::max();
int nearest_neigh_idx = -1;
for (int j = 0; j < N; ++j) {
if (min_dist[j] < nearest_neigh_dist) {
nearest_neigh_idx = j;
nearest_neigh_dist = min_dist[j];
}
}
// update relative distance to MST
for (int j = 0; j < N; ++j) {
if (min_dist[j] != std::numeric_limits<int>::max()) {
int new_dist = distance(points[j], points[nearest_neigh_idx]);
min_dist[j] = std::min(min_dist[j], new_dist);
}
}
// append point to MST
mst_cost += (long long) nearest_neigh_dist;
min_dist[nearest_neigh_idx] = std::numeric_limits<int>::max();
}
return mst_cost;
}
int main () {
if (freopen("metrou4.in", "r", stdin) == NULL) {
return 1;
}
if (freopen("metrou4.out", "w", stdout) == NULL) {
return 1;
}
std::vector<Point> points;
int T, ret;
ret = scanf("%d\n", &T);
if (ret != 1) {
fprintf(stderr,"Failure parsing input file!\n");
return 1;
}
while (T--) {
int N;
ret = scanf("%d\n", &N);
points.clear();
for (int i = 0; i < N; ++i) {
int X, Y;
ret = scanf("%d%d\n", &X, &Y);
points.push_back(Point(X, Y));
}
long long brute_cost = brute_prim(points);
printf("%lld\n", brute_cost);
}
return 0;
}