AtCoder Regular Contest 077 D Built?[最小生成树]
传送门:http://arc076.contest.atcoder.jp/tasks/arc076_b
Sample Input 1
3 1 5 3 9 7 8
Sample Output 1
3
Sample Input 2
6 8 3 4 9 12 19 18 1 13 5 7 6
Sample Output 2
8
题意:求1e5个点的最小生成树,每两个点a,b距离为min(|Xa-Xb|,|Ya-Yb|)。 kruskal求最小生成树 点数较多 考虑存在三个点a b c满足Xa<Xb<Xc 连接a和c花费为Xc-Xa,相比连接a,b和b,c 价格相同,所以后者连接了三个点更优
所以只需要分别排序后处理相邻点的2*(N-1)条边,复杂度nlogn。
代码:
1 #define _CRT_SECURE_NO_DEPRECATE 2 #pragma comment(linker, "/STACK:102400000,102400000") 3 #include<iostream> 4 #include<cstdio> 5 #include<fstream> 6 #include<iomanip> 7 #include<algorithm> 8 #include<cmath> 9 #include<deque> 10 #include<vector> 11 #include<assert.h> 12 #include<bitset> 13 #include<queue> 14 #include<string> 15 #include<cstring> 16 #include<map> 17 #include<stack> 18 #include<set> 19 #include<functional> 20 #define pii pair<int, int> 21 #define mod 1000000007 22 #define mp make_pair 23 #define pi acos(-1) 24 #define eps 0.00000001 25 #define mst(a,i) memset(a,i,sizeof(a)) 26 #define all(n) n.begin(),n.end() 27 #define lson(x) ((x<<1)) 28 #define rson(x) ((x<<1)|1) 29 #define inf 0x3f3f3f3f 30 typedef long long ll; 31 typedef unsigned long long ull; 32 using namespace std; 33 const int maxn = 1e5 + 5; 34 class node { 35 public: 36 int u, v, w; 37 node(int a, int b, int c) :u(a), v(b), w(c) {}; 38 }; 39 int fa[maxn]; 40 int getf(int i) { return i == fa[i] ? i : fa[i] = getf(fa[i]); } 41 vector<node>edge; 42 bool cmp(const node&a, const node&b){return a.w < b.w;} 43 class T { 44 public: 45 int value, id; 46 bool operator<(const T &a){return value < a.value;} 47 }; 48 T sx[maxn], sy[maxn]; 49 int main() 50 { 51 ios::sync_with_stdio(false); 52 cin.tie(0); 53 int i, j, k, m, n, ta, tb; 54 cin >> n; 55 for (int i = 1; i <= n; ++i) 56 fa[i] = i; 57 for (int i = 1; i <= n; ++i) 58 { 59 cin >> sx[i].value >> sy[i].value; 60 sx[i].id = sy[i].id = i; 61 } 62 sort(sx + 1, sx + n + 1); 63 sort(sy + 1, sy + 1 + n); 64 for (int i = 1; i < n; ++i) 65 { 66 edge.push_back(node(sx[i].id, sx[i + 1].id, sx[i+1].value - sx[i].value)); 67 edge.push_back(node(sy[i].id, sy[i + 1].id, sy[i+1].value - sy[i].value)); 68 } 69 sort(all(edge), cmp); 70 ll ans = 0; 71 for (int i = 0; i <edge.size(); ++i) 72 { 73 if (getf(edge[i].u) != getf(edge[i].v)) 74 { 75 ans += edge[i].w; 76 fa[getf(edge[i].u)] = getf(edge[i].v); 77 } 78 } 79 cout << ans << endl; 80 return 0; 81 }