观察木桩高度规律可知ai−ai−1=i
因此我们可以轻易得出ai=1+2+...+i
又由于b是ai雪面上的高度,因此雪厚为ai−b
时间复杂度为O(b−a)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int a,b;
int main() {
std::ios::sync_with_stdio(false); // 关闭同步,提高C++输入输出效率
cin>>a>>b;
long long s = 0;
for(int i=1;i<=b-a;i++)
{
s += i;
}
cout<<s-b;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int pre = sc.nextInt(),after =sc.nextInt();
int[] height = new int[1000];
height[0] = 1;
for(int i=1;i<1000;i++){
height[i] = height[i-1]+i+1;
}
for(int i=1;i<1000;i++){
if(height[i-1]-pre==height[i]-after){
System.out.println(height[i]-after);
return;
}
}
}
}
def find_snow_thickness(a, b):
# 逐步找到对应的桩子的高度
i = 1
while True:
h1 = i * (i + 1) // 2 # 第i个桩子的高度
h2 = (i + 1) * (i + 2) // 2 # 第i+1个桩子的高度
if h1 + (b - a) == h2:
return h1 - a
i += 1
# 读取输入
a, b = map(int, input().split())
# 计算雪的厚度
result = find_snow_thickness(a, b)
# 输出结果
print(result)
村子里有一些桩子,从左到右高度依次为1,1+2,1+2+3,…,每两颗桩子之间的间隔为1。
现在下了一场大雪,但是不知道雪下了多厚,现在给你两个数字,这是雪后某相邻两个桩子在雪面的高度,请你通过这两个数字计算雪的厚度。
第一行输入两个整数a,b
1≤a<b≤5∗105
一个整数代表答案,保证答案存在
输入
8 13
输出
2
说明
高度依次是1,3,6,10,15,.给出的是第4个和第5个子雪面上的高度所以雪的厚度是2
输入
10 15
输出
0