牛客OI周賽8-提高組 — 用水填坑

題目挺好的,不過自己不太會,用到優先隊列的bfs,不錯

傳送門

解題思路:

  • 給我們一個水池,我們想讓裏面的水最多,也就是慢慢找唄,
  • 首先這個池子能存多少水(假設先是一圈牆),取決於這個牆的最低高度是多少,所以我們因此可以想到我們每次都是用最低的牆是進行搜索
  • 首先我們利用貪心的思想,首先計算周圍的牆(也就是最邊上的牆),然後我們找高度最低的牆往裏縮小(因此如果不找最小,如果水高於那個最小位置,那麼水會溢出),所以從周圍的最小值開始找起,如果找到比他高的,先暫時存入隊列不用管,如果找到比他小的,那麼證明這個比他小的位置可以儲存水,因爲周圍都是比他高的(當前的值是周圍的最小值),所以加上高度,然後把這個值變爲圍牆的最小值(這個地方好坑,一開始沒注意),然後排着搜索就行,可以參照代碼來看。

代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

typedef pair<int,pair<int,int>> PII;
typedef long long ll;

const int N = 1010;

bool st[N][N];
int ans[N][N];
int idx[4] = {0,0,1,-1}, idy[4] = {1,-1,0,0};

priority_queue<PII,vector<PII>,greater<PII>> q;

int main(){
    int n, m;
    scanf("%d%d",&n,&m);
    for (int i = 1; i <= n;i ++){
    	for (int j = 1; j <= m; j++){
    		scanf("%d",&ans[i][j]);
    		if (i == 1 || j == 1 || i == n || j == m){
    			q.push({ans[i][j],{i,j}});
    			st[i][j] = true;
    		}
    	}
    }
    ll res = 0;
    while(!q.empty()){
    	auto t = q.top();
    	q.pop();
    	int x = t.second.first;
    	int y = t.second.second;
    	for (int i = 0; i < 4 ; i++){
    		int xx = x + idx[i];
    		int yy = y + idy[i];
    		if (xx < 1 || xx > n || yy < 1 || yy > m || st[xx][yy]) continue;

    		st[xx][yy] = true;

    		if (t.first > ans[xx][yy]){
    			res += t.first - ans[xx][yy];
    			ans[xx][yy] = t.first;
    		}
    		q.push({ans[xx][yy],{xx,yy}});
    	}

    }
    printf("%lld\n",res);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章