0
点赞
收藏
分享

微信扫一扫

AcWing 4377. 农田灌溉(BFS)

janedaring 2022-03-22 阅读 76

原题链接

4377. 农田灌溉 - AcWing题库icon-default.png?t=M276https://www.acwing.com/problem/content/4380/

普通做法

#include<iostream>
#include<algorithm>
using namespace std;

const int N = 210;
int n,m;
int T;
int p[N];


int main() {
	
	cin>>T;
	
	while(T--) {
		
		int res =0;
		
		cin>>n>>m;

		for(int i =1; i<=m; i++) {

			cin>>p[i];
		}
		res = max(p[1],n-p[m]+1);
		
		for(int i =1;i<m;i++){
			
			res = max(res,(p[i]+p[i+1])/2-p[i]+1);
		}
		
		cout<<res<<endl;
	}





	return 0;
}

BFS做法(转载自:AcWing 4377. 农田灌溉——bfs写法c++ - AcWing)

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;

const int N = 210;

queue<int> q;
bool st[N];
int d[N];
int n,m;
int maxv = 1;

int bfs()
{
	while(q.size()){
		
		int t = q.front();q.pop();
		
		//往左右两边浇水 
		//左 
		if(t>=2 && st[t-1] == false){
			
			d[t-1] = d[t]+1;
			maxv = max(maxv,d[t-1]);
			st[t-1] = true;
			q.push(t-1);

		}
		//右
		if(t<=n-1&&st[t+1]==false){
			
			d[t+1] = d[t]+1;
			maxv = max(maxv,d[t+1]);
			st[t+1] = true;
			q.push(t+1);
		} 
		
	}
	
	return maxv;
}

int main()
{
	
	
	int T;cin>>T;
	while(T--){
		//初始化 
		memset(st,false,sizeof st);
		memset(d,0,sizeof d);
		maxv = 1;
		cin>>n>>m;
		while(m--){
			
			int x;cin>>x;
			d[x] = 1;
			q.push(x);
			st[x] = true; 
		}
		
		cout<<bfs()<<endl;
	}
}
举报

相关推荐

0 条评论