0
点赞
收藏
分享

微信扫一扫

蓝桥杯训练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;
	}
}

请添加图片描述

举报

相关推荐

0 条评论