P3073 [USACO13FEB]Tractor S 二分+dfs 或 kruscal最小生成树

One of Farmer John’s fields is particularly hilly, and he wants to purchase a new tractor to drive around on it. The field is described by an N x N grid of non-negative integer elevations (1 <= N <= 500). A tractor capable of moving from one grid cell to an adjacent cell (one step north, east, south, or west) of height difference D costs exactly D units of money.

FJ would like to pay enough for his tractor so that, starting from some grid cell in his field, he can successfully drive the tractor around to visit at least half the grid cells in the field (if the number of total cells in the field is odd, he wants to visit at least half the cells rounded up). Please help him compute the minimum cost necessary for buying a tractor capable of this task.
输入格式

  • Line 1: The value of N.

  • Lines 2…1+N: Each line contains N space-separated non-negative integers (each at most 1 million) specifying a row of FJ’s field.
    输出格式

  • Line 1: The minimum cost of a tractor that is capable of driving around at least half of FJ’s field.
    题意翻译

题目描述

FJ有块农田太崎岖了,他要买一辆新拖拉机才能在这里巡视。这块农田由N x N个格子的非负整数表示高度(1<=N<=500)。拖拉机从当前格子走到相邻格子(东、南、西、北四个方向)的代价为高度差D,则FJ驶过这两个格子的拖拉机最少也要值D块钱。

FJ愿意花足够的钱买一辆新的拖拉机使得他能以最小的高度差走遍所有格子的一半(如果格子总数是奇数,那么一半的值为四舍五入的值)。因为FJ很懒,所以他找到你帮他编程计算他最小需要花多少钱买到符合这些要求的拖拉机。

输入输出格式

输入格式:

第一行为一个整数N

第2到N+1行每行包含N个非负整数(不超过1,000,000),表示当前格子的高度。

输出格式:

共一行,表示FJ买拖拉机要花的最小价钱。
输入输出样例
输入 #1

5 
0 0 0 3 3 
0 0 0 0 3 
0 9 9 3 3 
9 9 9 3 3 
9 9 9 9 3 

输出 #1

3 

题意 : 给个500*500的网格,走到相邻格子需要花费高度差abs(mtx[i][j]-mtx[i2][j2])
的价格,定义一条合格路为经过至少n*n/2的个格子,买一台拖拉机要花费合格路的相邻格子最大高度差
问最少花费多少钱.

题意 : 给个500*500的网格,相邻两个格子高度差小于等于K就可以视为在一个联通块内,
k最小是多少才能保证 : 网格内有一个至少包含n*n/2个格子联通块.

解法一 :

  • 二分猜这个 K值,
  • k太小时一定无法连成大小为n*n/2的联通块,所以尝试更大的答案lef = mid + 1
  • k太大时一定可以连成大小为n*n/2的联通块,所以尝试更小的答案rig = mid
  • 判断最大联通块个数用dfs即可
  • 时间复杂度 O (    n 2 l o g ( 1 e 9 )    ) O(~~n^2log(1e9)~~) O(  n2log(1e9)  )

解法二 :

  • 把所有格子编号,相邻格子连边,边权为高度差,于是得到一张无向图
  • 对这张图kruscal求最小生成树,维护并查集大小size,
    size大于等于一半的时候输出当前边就是答案
//二分 + dfs
#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <stdlib.h>
#include <queue>
#include <math.h>

#define MAXN (512)
#define ll long long 
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;

#ifdef debug
#define show(x...)                                 \
	do {                                           \
		cout << "\033[31;1m " << #x << " -> ";     \
		err(x);                                    \
	} while (0) 
#else
#define show(x...)  
#endif

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO {

	char print_f[105];
	void read() { }
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
		inline void read(T &x, T2 &... oth) {
			x = 0;
			char ch = getchar();
			ll f = 1;
			while (!isdigit(ch)) {
				if (ch == '-') f *= -1; 
				ch = getchar();
			}
			while (isdigit(ch)) {
				x = x * 10 + ch - 48;
				ch = getchar();
			}
			x *= f;
			read(oth...);
		}
	template <typename T>
		inline void put(T x) {
			if(x==0) { putchar('0'); putchar('\n'); return; }
			if(x<0) { putchar('-'); x = -x; }
			int num=0;
			char ch[128];
			while(x) ch[++num] = x % 10 + '0', x /= 10;
			while(num) putchar(ch[num--]);
			putchar('\n');
		}
}; // namespace FastIO
using FastIO::read;
using FastIO::put;

int n, m, Q, K;

bool vis[MAXN][MAXN];
int mtx[MAXN][MAXN], cnt, tmax;

int dr[] = { 0, 0, 1, -1 };
int dc[] = { 1, -1, 0, 0 };

inline int intabs(int x) { return x > 0 ? x : -x ; }

void dfs(int r, int c) { //计算联通块
	vis[r][c] = true;
	cnt ++;
	for(int i=0; i<4; i++) {
		int nr = r + dr[i], nc = c + dc[i];
		int tmp = abs(mtx[r][c] - mtx[nr][nc]);
		if(nr >= 1 && nc >= 1 && nr <= n && nc <= n && 
				!vis[nr][nc] && abs(tmp) <= K)
			dfs(nr, nc);
	}
}

bool check(int mid) { //判断给定高度差mid内是否有大小大于等于n*n/2的联通块
	memset(vis, false, sizeof(vis));
	K = mid;
	fori(1, n)
		forj(1, n) {
			if(vis[i][j]) continue ;
			cnt = 0;
			dfs(i, j);
			if(cnt >= m) return true;
		}
	return false;
}

signed main() {
#ifdef debug
	freopen("test", "r", stdin);
	// freopen("out_main", "w", stdout);
	clock_t stime = clock();
#endif
	read(n);
	fori(1, n)
		forj(1, n) read(mtx[i][j]);
	
	int lef = 0, rig = 1e9, mid;
	m = (n * n >> 1) + (n * n & 1);
	while(lef < rig) {
		mid = (lef + rig) >> 1;
		bool ret = check(mid);
		if(ret) 
			rig = mid;
		else
			lef = mid + 1;
	}
	printf("%d\n", lef);


















#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}





解法二代码

//kruscal最小生成树
#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <stdlib.h>
#include <math.h>

#define MAXN (512)
#define ll long long 
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;

#ifdef debug
#define show(x...)                                 \
	do {                                           \
		cout << "\033[31;1m " << #x << " -> ";     \
		err(x);                                    \
	} while (0) 
#else
#define show(x...)  
#endif

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO {

	char print_f[105];
	void read() { }
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
		inline void read(T &x, T2 &... oth) {
			x = 0;
			char ch = getchar();
			ll f = 1;
			while (!isdigit(ch)) {
				if (ch == '-') f *= -1; 
				ch = getchar();
			}
			while (isdigit(ch)) {
				x = x * 10 + ch - 48;
				ch = getchar();
			}
			x *= f;
			read(oth...);
		}
	template <typename T>
		inline void put(T x) {
			if(x==0) { putchar('0'); putchar('\n'); return; }
			if(x<0) { putchar('-'); x = -x; }
			int num=0;
			char ch[128];
			while(x) ch[++num] = x % 10 + '0', x /= 10;
			while(num) putchar(ch[num--]);
			putchar('\n');
		}
}; // namespace FastIO
using FastIO::read;
using FastIO::put;

int n, m, Q, K, ez;
#if 1
int M = 4;
int dr[] = { 0, 0, 1, -1 };
int dc[] = { 1, -1, 0, 0 };
#else
int M = 2;
int dr[] = { 0, 1 };
int dc[] = { 1, 0 };
#endif

int mtx[512][512];

struct Edge {
	int u, v, w;
	bool operator < (const Edge& no) const {
		return w < no.w;
	}
} ed[1000010];

int pre[250010], sum[250010];
int fa(int x) {
	return x == pre[x] ? x : (pre[x]=fa(pre[x]));
}

void union_xy(int x, int y) {
	x = fa(x), y = fa(y);
	if(x != y) {
		sum[x] += sum[y];
		pre[y] = x;
	}
}

void krs() {
	sort(ed+1, ed+1+m);
	int i = 1, tmax = 1;
	K = n * n;
	for(i=1; i<=n*n; i++) pre[i] = i, sum[i] = 1;
	K --;
	for(i=1; i<=m && K && tmax<(n*n/2); i++) {
		if(fa(ed[i].u) == fa(ed[i].v)) continue ;
		union_xy(ed[i].u, ed[i].v);
		tmax = max(tmax, sum[fa(ed[i].u)]);
	}
	printf("%d\n", ed[i-1].w);
}

signed main() {
#ifdef debug
	freopen("test", "r", stdin);
	// freopen("out_main", "w", stdout);
	clock_t stime = clock();
#endif
	read(n);
	fori(1, n)
		forj(1, n)
			read(mtx[i][j]);
	fori(1, n)
		forj(1, n) {
			int u = (i-1) * n + j, v;
			for(int k=0; k<M; k++) {
				int nr = i + dr[k], nc = j + dc[k];
				if(!nr || nr>n || !nc || nc>n) continue ;
				v = (nr-1) * n + nc;
				ed[++m].u = u, ed[m].v = v;
				ed[m].w = abs((mtx[i][j] - mtx[nr][nc]));
			}
		}
	krs();














#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值