알고리즘 문제/BOJ
2887번 행성 터널
parkit
2019. 9. 28. 13:45
728x90
반응형
https://www.acmicpc.net/problem/2887
나는 x → y → z를 한 번에 정렬하여 순서대로 min 값을 찾는 방법을 생각하였으나
1 1000 3
1000 1000
위와 같은 좌표들이 있을 수도 있어서 반례가 생기고,
메모리 초과가 발생하였다.(N = 100,000)
알고 보니, 각각을 정렬하여 활용하는 방법이 있었다.
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 | #include <bits/stdc++.h> using namespace std; #define Max 100001 struct info { int x, y, z, num; }; struct info2 { int a, b, c; }; int N, parent[Max]; vector<info> v; vector<info2> mst; bool cmpx(const info & a, const info & b) { return a.x < b.x; } bool cmpy(const info & a, const info & b) { return a.y < b.y; } bool cmpz(const info & a, const info & b) { return a.z < b.z; } bool cmp(const info2 & a, const info2 & b) { return a.c < b.c; } int Find(int x) { if (parent[x] == x) return x; return parent[x] = Find(parent[x]); } void Union(int a, int b) { a = Find(a); b = Find(b); if (a < b) parent[b] = a; else parent[a] = b; } int main(void) { //cin.tie(0); int x, y, z, cnt = 0, answer = 0; scanf("%d", &N); for (int i = 0; i < N; i++) { parent[i] = i; scanf("%d %d %d", &x, &y, &z); v.push_back({ x, y, z, i }); } // x sort(v.begin(), v.end(), cmpx); for (int i = 0; i < v.size() - 1; i++) mst.push_back({ v[i].num, v[i + 1].num, abs(v[i].x - v[i + 1].x) }); // y sort(v.begin(), v.end(), cmpy); for (int i = 0; i < v.size() - 1; i++) mst.push_back({ v[i].num, v[i + 1].num, abs(v[i].y - v[i + 1].y) }); // z sort(v.begin(), v.end(), cmpz); for (int i = 0; i < v.size() - 1; i++) mst.push_back({ v[i].num, v[i + 1].num, abs(v[i].z - v[i + 1].z) }); sort(mst.begin(), mst.end(), cmp); for (auto i : mst) if (Find(i.a) != Find(i.b)) { Union(i.a, i.b); answer += i.c; if (++cnt == N - 1) break; } printf("%d\n", answer); return 0; } | cs |
728x90
반응형