蓝桥杯训练1——贪心算法——安置路灯

安置路灯(题目来自牛客网)


请添加图片描述

思路解读

由数据输入范围为1e6,故可猜测算法可用时间复杂度为O(n)
遇到.的情况才需要照明,当遇到X的时候无需照明,若当前位置为. ,且下一个位置不为.,为X,则必须设置一个路灯,若当前位置为.,且下一个位置也是.,则将路灯设置在下一个位置,而无需管当前位置的下2个位置是X还是.,直接跳过,故有代码。

AC代码

import java.io.*;

public class Main{
	public static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	public static void main(String[] args) throws Exception{
		String s = bf.readLine();
		int n = Integer.parseInt(s);
		s = bf.readLine();
		char [] str = new char[n];
		str = s.toCharArray();
		int ans = 0;
		boolean flag = false;
		for(int i=0;i<n;i++) {
			if(!flag && str[i] == '.' && i + 1 < n && str[i + 1] == '.') {
				flag = true;
			}else if(!flag && str[i] == '.') {
				ans ++;
			}else {
				if(flag && str[i] == '.') {
					flag = false;
					ans ++;
					i++;
				}
			}
		}
		System.out.println(ans);
	
	}
}

递归算法

本来打算采用递归算法,但是采用递归算法后,发生栈越界,想想也是,栈不能存那么那么多数

import java.io.*;

public class Main{
	public static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	public static void main(String[] args) throws Exception{
		String s = bf.readLine();
		int n = Integer.parseInt(s);
		s = bf.readLine();
		char [] str = new char[n];
		str = s.toCharArray();
		System.out.println(f(str,0));
	}
	public static int f(char [] s, int x) {
		if(x >= s.length)
			return 0;
		if(s[x] == '.') {
			if(x+1 < s.length && s[x+1] == '.')
				return 1 + f(s,x+3);
			else 
				return 1 + f(s,x+2);
		}else {
			return f(s,x+1);
		}
	}
}

请添加图片描述

所以需要将递归改为递推

递推AC代码(其实和上一个代码是一样的)

import java.io.*;

public class Main{
	public static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	public static void main(String[] args) throws Exception{
		String s = bf.readLine();
		int n = Integer.parseInt(s);
		s = bf.readLine();
		char [] str = new char[n];
		str = s.toCharArray();
		System.out.println(f(str));
	}
	public static int f(char [] s) {
		int ans = 0;
		int n = s.length;
		int x = 0;
		while(x < n) {
			if(s[x] == '.') {
				if(x + 1 < n && s[x + 1] == '.') {
					ans ++;
					x +=3;
				}else {
					ans ++;
					x +=2;
				}
			}else {
				x++;
			}
		}
		return ans;
	}
}

请添加图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜡笔里没小新诶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值