Java教程

题解 第二题

本文主要是介绍题解 第二题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

传送门

很容易想到二分答案,关键是check怎么写
考虑如何消除后效性
发现如果每次取最高的点更新周围点的高度,那每个点只会被更新一次
维护一个堆每次取最大值就好了

Code:

#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define N 100010
#define ll long long
#define fir first
#define sec second
#define make make_pair
#define reg register int
//#define int long long 

char buf[1<<21], *p1=buf, *p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf, 1, 1<<21, stdin)), p1==p2?EOF:*p1++)
inline ll read() {
	ll ans=0, f=1; char c=getchar();
	while (!isdigit(c)) {if (c=='-') f=-f; c=getchar();}
	while (isdigit(c)) {ans=(ans<<3)+(ans<<1)+(c^48); c=getchar();}
	return ans*f;
}

int r, c; ll k, maxn;
bool* vis[N];
ll *mp[N], *tem[N];
const int dlt[][2]={{0,-1},{0,1},{-1,0},{-1,1},{1,-1},{1,0}};

namespace force{
	struct ele{ll val; int x, y; ele(){} ele(ll v, int a, int b):val(v),x(a),y(b){}};
	inline bool operator < (ele a, ele b) {return a.val<b.val;};
	priority_queue<ele> q;
	bool check(ll d) {
		ll rest=k;
		while (q.size()) q.pop();
		for (reg i=1; i<=r; ++i) for (reg j=1; j<=c; ++j) tem[i][j]=mp[i][j];
		for (reg i=1; i<=r; ++i) memset(vis[i], 0, sizeof(bool)*(c+5));
		for (reg i=1; i<=r; ++i) for (reg j=1; j<=c; ++j) q.push(ele(mp[i][j], i, j));
		ele t;
		while (q.size()) {
			t=q.top(); q.pop();
			//cout<<"val: "<<t.val<<endl;
			if (vis[t.x][t.y]) continue;
			vis[t.x][t.y]=1;
			for (reg i=0,x,y; i<6; ++i) {
				x=t.x+dlt[i][0], y=t.y+dlt[i][1];
				if (x<1||x>r||y<1||y>c) continue;
				if (tem[t.x][t.y]-tem[x][y]>d) {
					rest-=(tem[t.x][t.y]-tem[x][y]-d);
					if (rest<0) return 0;
					tem[x][y]=tem[t.x][t.y]-d;
					q.push(ele(tem[x][y], x, y));
				}
			}
		}
		return 1;
	}
	void solve() {
		ll l=0, r=maxn+10, mid;
		while (l<=r) {
			mid=(l+r)>>1;
			if (!check(mid)) l=mid+1;
			else r=mid-1;
		}
		printf("%lld\n", l);
		exit(0);
	}
}

signed main()
{
	r=read(); c=read(); k=read();
	for (int i=0; i<=r+1; ++i) mp[i]=new ll[c+10];
	for (int i=0; i<=r+1; ++i) tem[i]=new ll[c+10];
	for (int i=0; i<=r+1; ++i) vis[i]=new bool[c+10];
	for (reg i=1; i<=r; ++i) for (reg j=1; j<=c; ++j) mp[i][j]=read(), maxn=max(maxn, mp[i][j]);
	force::solve();
	
	return 0;
}
这篇关于题解 第二题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!