題目描述
在一個遙遠的國度,一側是風景秀美的湖泊,另一側則是漫無邊際的沙漠。該國的行政區劃十分特殊,剛好構成一個 N行 M 列的矩形,如上圖所示,其中每個格子都代表一座城市,每座城市都有一個海拔高度。
爲了使居民們都儘可能飲用到清澈的湖水,現在要在某些城市建造水利設施。水利設施有兩種,分別爲蓄水廠和輸水站。蓄水廠的功能是利用水泵將湖泊中的水抽取到所在城市的蓄水池中。因此,只有與湖泊毗鄰的第 1 行的城市可以建造蓄水廠。而輸水站的功能則是通過輸水管線利用高度落差,將湖水從高處向低處輸送。故一座城市能建造輸水站的前提,是存在比它海拔更高且擁有公共邊的相鄰城市,已經建有水利設施。
由於第 N 行的城市靠近沙漠,是該國的乾旱區,所以要求其中的每座城市都建有水利設施。那麼,這個要求能否滿足呢?如果能,請計算最少建造幾個蓄水廠;如果不能,求乾旱區中不可能建有水利設施的城市數目。
輸入
輸入文件的每行中兩個數之間用一個空格隔開。
輸入的第一行是兩個正整數 N和 M,表示矩形的規模。
接下來 N行,每行 M 個正整數,依次代表每座城市的海拔高度。
輸出
輸出有兩行。如果能滿足要求,輸出的第一行是整數 1,第二行是一個整數,代表最少建造幾個蓄水廠;如果不能滿足要求,輸出的第一行是整數 0,第二行是一個整數,代表有幾座乾旱區中的城市不可能建有水利設施。
樣例
輸入1
2 5
9 1 5 4 3 1
8 7 6 1 2
輸出1
1
輸入2
3 6
8 4 5 6 4 4
7 3 4 3 3 3
3 2 2 1 1 2
輸出2
1
3
提示
【樣例 1 說明】
只需要在海拔爲 9 的那座城市中建造蓄水廠,即可滿足要求。
【樣例 2 說明】
上圖中,在 3 個粗線框出的城市中建造蓄水廠,可以滿足要求。以這 3個蓄水廠爲源頭在乾旱區中建造的輸水站分別用3種顏色標出。當然,建造方法可能不唯一。
傳送門
滿分代碼:
const h:array[1..4,1..2] of longint=((1,0),(-1,0),(0,-1),(0,1));
var col,a:array[0..501,0..501] of longint;
f:array[0..500] of longint;
c:array[0..500,1..2] of longint;
d:array[0..500000] of record x,y:longint;end;
n,m,i,j,color:longint;
function min(a,b:longint):longint;
begin if a<b then exit(a) else exit(b); end;
procedure Judge;
var i,j:longint;
procedure bfs(x,y:integer);
var i,t,f:longint;
begin
t:=1;f:=1;
d[t].x:=x;d[t].y:=y;
col[x,y]:=color;
repeat
for i:=1 to 4 do
if col[d[f].x+h[i,1],d[f].y+h[i,2]]=0 then
if a[d[f].x+h[i,1],d[f].y+h[i,2]]<a[d[f].x,d[f].y] then begin
inc(t);
d[t].x:=d[f].x+h[i,1]; d[t].y:=d[f].y+h[i,2];
col[d[t].x,d[t].y]:=color;
end;
inc(f);
until f>t;
end; {end bfs}
begin {judge}
for i:=0 to n+1 do begin
a[i,0]:=maxlongint;
a[i,m+1]:=maxlongint;
end;
for i:=0 to m+1 do begin
a[0,i]:=maxlongint;
a[n+1,i]:=maxlongint;
end;
for color:=1 to m do bfs(1,color);
j:=0;
for i:=1 to m do
if col[n,i]=0 then inc(j);
if j>0 then begin
writeln(0);
writeln(j);
halt;
end;
end;
procedure floodfill;
procedure bfs(x,y:integer);
var i,t,f:longint;
begin
t:=1;f:=1;
d[t].x:=x;d[t].y:=y;
col[x,y]:=color;
repeat
for i:=1 to 4 do
if col[d[f].x+h[i,1],d[f].y+h[i,2]]=0 then
if a[d[f].x+h[i,1],d[f].y+h[i,2]]>a[d[f].x,d[f].y] then begin
inc(t);
d[t].x:=d[f].x+h[i,1]; d[t].y:=d[f].y+h[i,2];
col[d[t].x,d[t].y]:=color;
end;
inc(f);
until f>t;
end;
var i,j:longint;
begin
for i:=0 to n+1 do begin
a[i,0]:=0; a[i,m+1]:=0;
end;
for i:=0 to m+1 do begin
a[0,i]:=0; a[n+1,i]:=0;
end;
fillchar(col,sizeof(col),0);
for color:=1 to m do
if col[n,color]=0 then
bfs(n,color);
for i:=1 to m do
c[i,1]:=col[1,i];
fillchar(col,sizeof(col),0);
for color:=m downto 1 do
if col[n,color]=0 then bfs(n,color);
for i:=1 to m do c[i,2]:=col[1,i];
end;
procedure DP;
var i,j:longint;
begin
f[0]:=0;
for i:=1 to m do
begin
f[i]:=maxint;
for j:=1 to m do
if (c[j,2]>=i)and(c[j,1]<=i) then
f[i]:=min(f[i],f[c[j,1]-1]+1);
end;
writeln(1);
writeln(f[m]);
end;
BEGIN {main}
read(n,m);
for i:=1 to n do
for j:=1 to m do
read(a[i,j]);
judge;
floodfill;
DP;
END.