码迷,mamicode.com
首页 > 其他好文 > 详细

5.26每日一题题解

时间:2020-05-26 15:09:15      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:队列   cto   while   lse   heap   --   top   code   知识   

A - 用水填坑

涉及知识点:

  • 优先队列/BFS

solution:

  • 首先将这块地的四边放入优先队列,以它为这个水坑的边界
  • 每次取出边界上最小的数,然后搜索它上下左右四个点
  • 如果这些点里有比它小的,就说明将这个坑的水填到和取出的数一样高水不会溢出
  • 为什么要取最小的数可以想一下木桶效应
  • 然后把遍历的上下左右四个点作为新的边界继续进行上述步骤,直到遍历完所有的数

std:

#include <bits/stdc++.h>

using namespace std;

typedef unsigned long long ull;
typedef pair<int,pair<int,int>> PII; 

const int N = 1010;

int a[N][N];
bool st[N][N];
int dx[]={-1,1,0,0},dy[] = {0,0,1,-1};
int n,m;
priority_queue<PII , vector<PII>, greater<PII> >heap;

int main()
{
    scanf("%d%d",&n,&m);
    for (int i = 1 ; i <= n ; i ++ )
    {
        for (int j = 1 ; j <= m ; j ++ )
        {
            scanf("%d",&a[i][j]);
            if(i == 1 || j == 1 || i == n || j == m)
            {
                st[i][j] = true;
                heap.push({a[i][j],{i,j}});
            }
        }
    }
    
    ull res = 0;
    while(!heap.empty())
    {
        auto t = heap.top();
        heap.pop();
        for (int i = 0 ; i < 4 ; i ++ )
        {
            int x = t.second.first + dx[i];
            int y = t.second.second + dy[i];
            if(x < 1 || y < 1 || x > n || y > m || st[x][y]) continue;
            else
            {
                if(a[x][y] < t.first)
                {
                    res += t.first - a[x][y];
                    a[x][y] = t.first;
                }
                heap.push({a[x][y],{x,y}});
                st[x][y] = true;
            }
        }
    }
    printf("%lld\n",res);
    return 0;
}

5.26每日一题题解

标签:队列   cto   while   lse   heap   --   top   code   知识   

原文地址:https://www.cnblogs.com/QFNU-ACM/p/12965619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!