1 条题解
-
0xuyifeng LV 10 MOD @ 2017-10-03 21:02:42
//---------------------------------------------AC code---------------------------------------------//
#include<algorithm> #include<iostream> #include<cstdio> #define f(a, b) ((a-1)*m+b) using namespace std; const int MAXN = 305; int n, m, h[MAXN][MAXN], num; int fa[MAXN*MAXN]; struct E{ int from, to, dis; }e[MAXN*MAXN<<1]; int e_n; void a_e(int from, int to, int dis){ e[++e_n].from = from; e[e_n].to = to; e[e_n].dis = dis; } struct Edge{ int nxt, to, dis; }edge[MAXN*MAXN<<1]; int head[MAXN*MAXN], edge_num; void add_edge(int from, int to, int dis){ edge[++edge_num].nxt = head[from]; edge[edge_num].to = to; edge[edge_num].dis = dis; head[from] = edge_num; edge[++edge_num].nxt = head[to]; edge[edge_num].to = from; edge[edge_num].dis = dis; head[to] = edge_num; } bool cmp(E a, E b){ return a.dis < b.dis; } int findfa(int x){ if(x != fa[x]) fa[x] = findfa(fa[x]); return fa[x]; } void unionn(int x, int y){ fa[findfa(y)] = findfa(x); } void kruskal(){ sort(e+1, e+e_n+1, cmp); int u = 0; for(int i = 1; i <= e_n; i++){ if(findfa(e[i].from) != findfa(e[i].to)){ unionn(e[i].from, e[i].to); add_edge(e[i].from, e[i].to, e[i].dis); u++; if(u == n*m) break; } } } int ans[MAXN*MAXN]; void dfs(int x, int f, int maxx){ ans[x] = maxx; for(int i = head[x]; i; i = edge[i].nxt){ if(edge[i].to == f) continue; dfs(edge[i].to, x, max(maxx, edge[i].dis)); } } int main(){ scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) scanf("%d", &h[i][j]), fa[f(i, j)] = f(i, j); int S = n*m+1; for(int i = 1; i <= n; i++) a_e(f(i, 1), S, max(0, h[i][1])), a_e(f(i, m), S, max(0, h[i][m])); for(int i = 1; i <= m; i++) a_e(f(1, i), S, max(0, h[1][i])), a_e(f(n, i), S, max(0, h[n][i])); for(int i = 1; i < n; i++){ for(int j = 1; j < m; j++){ a_e(f(i, j), f(i, j+1), max(h[i][j], h[i][j+1])); a_e(f(i, j), f(i+1, j), max(h[i][j], h[i+1][j])); } } kruskal(); dfs(S, 0, 0); for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++) printf("%d ", ans[f(i, j)] - h[i][j]); putchar(10); } return 0; }
- 1