一开始用的BFS+DP 改成BFS+贪心之后错了 求调
查看原帖
一开始用的BFS+DP 改成BFS+贪心之后错了 求调
421758
HANDSOME_FZZ楼主2023/7/20 17:28
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <utility>
#define N 505
using namespace std;
int n,m,h[N][N],ans,dp[N];
bool vis[N][N],w[N],t[N][N];
int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};

struct tower{
	int l,r;
}lq[N];

struct point{
	int x,y;
};

int read(){
	int x=0,f=1; char c;
	c=getchar();
	while(c<'0'||c>'9'){
		if(c=='-') f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9'){
		x=(x<<1)+(x<<3)+c-'0';
		c=getchar();
	}
	return x*f;
}

void loading(){
	n=read(); m=read();
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++) h[i][j]=read();
}

bool ok(int x,int y,int nx,int ny){
	if(nx<1||nx>n||ny<1||ny>m||vis[nx][ny]||h[nx][ny]>=h[x][y]) return 0;//越界
	return 1;
}

void bfs(int x,int y){
	if(t[x][y]) return;
	memset(vis,0,sizeof(vis));
	memset(w,0,sizeof(w));
	point now={x,y}; bool z=0;
	//cout<<now.x<<' '<<now.y<<endl;
	queue<point>q; q.push(now);
	vis[x][y]=1; t[x][y]=1;
	while(!q.empty()){
		now=q.front(); q.pop();
		//cout<<now.x<<' '<<now.y<<endl;
		if(now.x==n){ w[now.y]=1; z=1;}
		for(int i=0;i<4;i++){
			int nx=now.x+d[i][0],ny=now.y+d[i][1];
			if(ok(now.x,now.y,nx,ny)){
			//	cout<<now.x<<' '<<now.y<<' '<<nx<<' '<<ny<<endl;
				point p={nx,ny};
				q.push(p); vis[nx][ny]=1; //不重复加点 
				t[nx][ny]=1;//判断能否到达 vis每轮都要清空 
			}
		}
	}
	if(!z) return; int j=1;
	while(!w[j]) j++; lq[y].l=j;
	while(w[j]) j++; lq[y].r=j-1;//在y点修蓄水池可以流到的区间左右端点 
	//cout<<lq[y].l<<' '<<lq[y].r<<endl;
}

void Dp(){
	for(int i=1;i<=m;i++) dp[i]=1e+9;
	for(int i=1;i<=m;i++)
		for(int j=1;j<=m;j++)
			if(lq[j].l<=i&&lq[j].r>=i) dp[i]=min(dp[i],dp[lq[j].l-1]+1);
}

bool cmp(tower a,tower b){
	return a.l<b.l||(a.l==b.l&&a.r>b.r);
}

void Tx(){//贪心 
	sort(lq+1,lq+m+1,cmp);
	int i=1,j=1;
	while(i<=m){
		int t=0;
		while(lq[j].l<=i){
			t=max(lq[j].r,t);
			j++;
		}
		i=t+1; ans++;
	}
}

void out(){
	bool f=0;
	for(int i=1;i<=m;i++) if(!t[n][i]){ f=1; ans++;}
	if(f) printf("0\n%d",ans);
	else printf("1\n%d",ans);//dp[m]
}

int main(){
	loading();
	for(int i=1;i<=m;i++) bfs(1,i);
	//Dp();
	Tx();
	out();
	return 0;
} 
2023/7/20 17:28
加载中...