gpt4 book ai didi

java - 凯蒂斯有一个问题,我认为这是一个极端的例子

转载 作者:行者123 更新时间:2023-12-02 00:28:12 26 4
gpt4 key购买 nike

我需要一些 Kattis 练习的帮助 Neigborhood Watch 。由于答案错误,我在第十一次测试中失败了,我不知道为什么。如有任何帮助,我们将不胜感激。

詹妮弗被提名为邻里守望队长,现在负责管理她所在街道的守望。

詹妮弗的街道仅由路一侧的房屋组成。她制定了一个计划,其中的房屋将成为邻里看守所,并想知道该计划的安全性如何。如果沿途至少有一栋房子是邻里看守所,则从一栋房子步行到另一栋房子(不一定是不同的)就被认为是安全的。计划的安全评级是指在街道上安全行走的次数。由于步行要么安全,要么不安全,无论朝哪个方向行驶,安全评级都不会被计算两次。

告诉詹妮弗她的计划的安全评级。输入

第一行输入包含两个整数N (1≤N≤200000),这是街道上的房屋数量,K (0≤K≤N),是詹妮弗计划中邻里看守所的数量。房屋编号为 1,…,N。

接下来的 K 线描述了附近的看守所。每行都包含一个整数 H (1≤H≤N),它是附近看守所的门牌号。门牌号严格按照递增顺序给出。

输出

显示她的系统的安全等级(显示可能安全行走的次数)。

public class NeighborhoodWatch {

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String first[] = br.readLine().split(" ");
int n = Integer.parseInt(first[0]);
int k = Integer.parseInt(first[1]);
int ks[] = new int[k];
int x=0;
int y=k;
while (y>0) {
ks[x] = Integer.parseInt(br.readLine());
x++;
y--;
}
Arrays.sort(ks);
long count = 0;
//This loop runs through the safe houses(if they exist).
//It takes the remaining number of houses from the sad house onwards and multiplies it with the number of houses since the previous safe house. Which should be correct. And with a special case for the first one where you multiply by the number of houses to the first house on the street.
if (k>0) {
count = (n-ks[0]+1)*ks[0];
for(int i=1;i<k;i++) {
count += (n-ks[i]+1)*(ks[i]-ks[i-1]);
}
}
System.out.println(count);
}
}

示例:输入:

5 2

1

4

预期输出:

11

我把它放入黑匣子中进行测试,我通过了前 10 题,但在第 11 题得到了错误的答案。所以我假设这是我正在考虑的某种情况。

最佳答案

请注意,您无需对房屋进行排序,因为它们已按升序排列给您

我用Python解决了这个问题,我使用的方法是计算每个房子,靠近它的安全屋的第一个索引。我将步行到这个最初的安全屋视为长度为 1 的步行。然后我将安全屋之后的房屋数量相加,并将其添加到我的计数中。

例如,假设 N = 5,k = [3,4,5]。对于每栋房子:

  1. (1 -> 3 = 1) + (5 - 3) = 3
  2. (2 -> 3 = 1) + (5 - 3) = 3
  3. (3 -> 3 = 1) + (5 - 3) = 3
  4. (4 -> 4 = 1) + (5 - 4) = 2
  5. (5 -> 5 = 1) + (5 - 5) = 1

总共给出12

关于java - 凯蒂斯有一个问题,我认为这是一个极端的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com