保卫方案


一、题目论述:链接:https://www.nowcoder.com/questionTerminal/e1967ae812ea42e7a3ce57ee1f83b686来源:牛客网

战争游戏的至关重要环节就要到来了,这次的结果将决定王国的生死存亡,小B负责首都的防卫工作。首都位于一个四面环山的盆地中,周围的n个小山构成一个环,作为预警措施,小B计划在每个小山上设置一个观察哨,日夜不停的瞭望周围发生的情况。一旦发生外地入侵事件,山顶上的岗哨将点燃烽烟,若两个岗哨所在的山峰之间没有更高的山峰遮挡且两者之间有相连通路,则岗哨可以观察到另一个山峰上的烽烟是否点燃。由于小山处于环上,任意两个小山之间存在两个不同的连接通路。满足上述不遮挡的条件下,一座山峰上岗哨点燃的烽烟至少可以通过一条通路被另一端观察到。对于任意相邻的岗哨,一端的岗哨一定可以发现一端点燃的烽烟。 小B设计的这种保卫方案的一个重要特性是能够观测到对方烽烟的岗哨对的数量,她希望你能够帮她解决这个问题。

import java.util.Scanner;
import java.util.Stack;
public class Problem_04_MountainsAndFlames {
	//输入两行
	//第一行代表山的个数
	//第二行代表每座山的高度
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while (in.hasNextInt()) {
			int size = in.nextInt();
			int[] arr = new int[size];
			for (int i = 0; i < size; i++) {
				arr[i] = in.nextInt();
			}
			System.out.println(communications(arr));
		}
	}

	public static int nextIndex(int size, int i) {
		return i < (size - 1) ? (i + 1) : 0;
	}

	public static long getInternalSum(int n) {
		return n == 1L ? 0L : (long) n * (long) (n - 1) / 2L;
	}

	public static class Pair {
		public int value;
		public int times;

		public Pair(int value) {
			this.value = value;
			this.times = 1;
		}
	}

	public static long communications(int[] arr) {
		if (arr == null || arr.length < 2) {
			return 0;
		}
		int size = arr.length;
		int maxIndex = 0;
		//找到所有数中的最大值下标
		for (int i = 0; i < size; i++) {
			maxIndex = arr[maxIndex] < arr[i] ? i : maxIndex;
		}
		找到所有数中的最大值
		int value = arr[maxIndex];
		//获得最大值的下一个数的位置
		int index = nextIndex(size, maxIndex);
		long res = 0L;
		//初始化栈,里面装的为Pair元素
		Stack<Pair> stack = new Stack<>();
		//将最大值压栈
		stack.push(new Pair(value));
		while (index != maxIndex) {
			value = arr[index];
			//peek:查看栈顶对象而不移除
			while (!stack.isEmpty() && stack.peek().value < value) {
				//当前元素大于栈顶元素时,弹栈
				int times = stack.pop().times;
//				res += getInternalSum(times) + times;
//				res += stack.isEmpty() ? 0 : times;
				//times为这个数字出现的次数
				res += getInternalSum(times) + times*2;
			}
			//相等的话叠加次数
			if (!stack.isEmpty() && stack.peek().value == value) {
				stack.peek().times++;
			} else {
				//当前元素小于栈顶元素时压栈
				stack.push(new Pair(value));
			}
			//转到下一个元素
			index = nextIndex(size, index);
		}
		while (!stack.isEmpty()) {
			int times = stack.pop().times;
			res += getInternalSum(times);
			if (!stack.isEmpty()) {
				res += times;
				if (stack.size() > 1) {
					res += times;
				} else {
					res += stack.peek().times > 1 ? times : 0;
				}
			}
		}
		return res;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值