标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1961 Accepted Submission(s): 687
题解:裸的克鲁斯卡尔,由于只能相邻的连,所以只用给农田赋个编号就好了,然后排序最小生成树;
刚开始把MAP和Kruth开在栈里溢出了,放在全局就好了,因为全局变量是堆内存,也就是说只要不超过OJ给的最大内存限制,可以开很大的对象,但是栈内存一般只有2M的样子,而且里面还要存一些线程的基本信息和断点信息,所以实际可用的栈内存不到2M2M的话int数组最多开5e5的样子
---铭鑫学长 2016/4/8 10:45:58
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAXN = 1010; int disx[2] = {0,-1}; int disy[2] = {-1,0}; struct Node{ int x, y, v; friend bool operator < (Node a, Node b){ return a.v < b.v; } }; Node dt[MAXN * MAXN * 2]; int mp[MAXN][MAXN]; int hsh[MAXN][MAXN]; class Map{ private: int N, M; public: Map(){ N = 0; M = 0; } Map(int N, int M){ this->N = N; this->M = M; int tp = 0; for(int i = 1; i <= N; i++){ for(int j = 1; j <= M; j++){ scanf("%d",&mp[i][j]); hsh[i][j] = ++tp; } } } void getdt(int &tp){ // cout << N << " " << M << endl; for(int i = 1; i <= N; i++){ for(int j = 1; j <= M; j++){ for(int k = 0; k < 2; k++){ int nx, ny; nx = i + disx[k]; ny = j + disy[k]; if(nx <= 0 || ny <= 0 || nx > N || ny > M) continue; dt[tp].x = hsh[nx][ny]; dt[tp].y = hsh[i][j]; dt[tp].v = abs(mp[nx][ny] - mp[i][j]); tp++; } } } } }; int pre[MAXN * MAXN]; class Kruth{ private: public: Kruth(){ for(int i = 1; i <= MAXN * MAXN; i++){ pre[i] = i; } } int find(int r){ int x = r; while(r != pre[r]){ r = pre[r]; } int i = x, j; while(i != r){ j = pre[i]; pre[i] = r; i = j; } return r; } void merge(int x, int y, int v, int &ans){ int f1 = find(x), f2 = find(y); if(f1 != f2){ pre[f1] = f2; ans += v; } } }; int main(){ int T; int kase = 0; cin >> T; while(T--){ int N, M; cin >> N >> M; Map a(N,M); int tp = 0; int ans = 0; a.getdt(tp); sort(dt, dt + tp); Kruth kru; for(int i = 0; i < tp; i++){ kru.merge(dt[i].x, dt[i].y, dt[i].v, ans); } printf("Case #%d:\n%d\n",++kase,ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/5367146.html