乍一眼還以爲是水題,仔細一看發現還是有點難度的。。
首先我們考慮對於節點x,如果他上下左右的點有一個點已經放了抽水機且海拔比x低,則x不需要放抽水機。或者我們可以認爲我們花費代價0在x這個節點上放了一個抽水機
那麼我們把所有點關於海拔排序,那麼依次加入高度爲h的點後去判斷一下有沒有與已經放了抽水機的點相連,如果沒有則答案+1,並且在該點放上一個抽水機
這個操作可以用並查集或者直接BFS實現。。BFS感覺非城市節點的處理還是有點麻煩,所以我懶、、用並查集
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <string>
#include <map>
#include <cstring>
#include <ctime>
#include <vector>
#define inf 1e9
#define ll long long
#define maxn 20010
#define For(i,j,k) for(int i=j;i<=k;i++)
#define Dow(i,j,k) for(int i=k;i>=j;i--)
using namespace std;
inline void read(int &tx){ ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} tx=x*f; }
inline void write(ll x){ if (x<0) putchar('-'),x=-x; if (x>=10) write(x/10); putchar(x%10+'0'); }
inline void writeln(ll x){write(x);puts("");}
int dx[]={0,1,0,-1,0};
int dy[]={0,0,1,0,-1};
struct node{int x,y,v;}rou[1000001],cit[1000001];
bool ok[1000001];
int n,m,h[1011][1011],F[1000001],ans,tot,tot1;
inline bool cmp(node x,node y){return x.v<y.v;}
inline int c(int x,int y){return (x-1)*m+y;}
inline int get(int x){return x==F[x]?F[x]:F[x]=get(F[x]);}
inline void merge(int x,int y)
{
int tx=get(x),ty=get(y);
if(tx==ty) return;
F[ty]=tx;
}
int main()
{
read(n);read(m);
tot1=n*m;
For(i,1,n) For(j,1,m)
{
read(h[i][j]);
if(h[i][j]>0)
{
cit[++tot].x=i;cit[tot].y=j;
cit[tot].v=h[i][j];
}else h[i][j]=-h[i][j];
rou[c(i,j)].x=i;rou[c(i,j)].y=j;
rou[c(i,j)].v=h[i][j];
}
sort(cit+1,cit+tot+1,cmp);
sort(rou+1,rou+tot1+1,cmp);
int now=1;
for(int i=0;i<=n+1;i++)
h[i][0]=h[i][m+1]=inf;
for(int i=0;i<=m+1;i++)
h[0][i]=h[n+1][i]=inf;
For(i,1,tot1) F[i]=i;
For(i,1,tot)
{
for(;now<=tot1&&rou[now].v<=cit[i].v;now++)
{
int ny=rou[now].y,nx=rou[now].x;
For(d,1,4)
{
int tx=nx+dx[d],ty=ny+dy[d];
if(h[tx][ty]<=h[nx][ny])
{
ok[get(c(nx,ny))]|=ok[get(c(tx,ty))];
merge(c(nx,ny),c(tx,ty));
}
}
}
if(!ok[get(c(cit[i].x,cit[i].y))]) ok[get(c(cit[i].x,cit[i].y))]=1,ans++;
}
writeln(ans);
}
溫馨提示:注意卡常,我29s過的臥槽。。。