题目来源:码蹄集
题目描述:
B站老师思路讲解链接:https://www.bilibili.com/video/BV1MX4y1R77W/?t=54.3&vd_source=3ae2a916df1bc5c1114c2bf3e95a2118
C++代码实现:
参考原文链接:https://blog.csdn.net/m0_54754302/article/details/128277693
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
#define rall(a) a.rbegin(), a.rend()
#define fi first
#define se second
#define rep(i,s,n) for(int i=s; i<n; i++)
#define repd(i,s,n) for(int i=s; i>=n; i--)
const int MOD=1e9+7;
const int maxN=5e3+1;
const int INF=2e9;
const int MB=20;
const int MAX_LEN=200001;
ull s[MAX_LEN];
ull p[MAX_LEN];
void solve() {
ll n, x;
cin >> n >> x;
rep(i, 0, n) {
cin >> s[i];
p[i] = s[i];
}
ll pre = s[0];
rep(i, 1, n) {
sort(p, p+i);
ll temp;
rep(j, 0, i) {
temp = p[j] + x;
if (j == i-1)
break;
else {
if (p[j+1] - temp >= x)
break;
}
}
s[i] = temp > s[i] ? temp : s[i];
p[i] = s[i];
}
rep(i, 0, n)
cout << s[i] << " ";
}
int main() {
solve();
return 0;
}
Python代码实现:
import sys
def solve():
n, x = map(int, input().split())
s = list(map(int, input().split()))
p = s[:]
for i in range(1, n):
p[:i] = sorted(p[:i])
temp = 0
for j in range(i):
temp = p[j] + x
if j == i-1:
break
elif p[j+1] - temp >= x:
break
s[i] = max(temp, s[i])
p[i] = s[i]
print(*s)
def main():
solve()
if __name__ == "__main__":
main()
Java代码实现:
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x = sc.nextInt();
int[] s = new int[n];
int[] p = new int[n];
for (int i = 0; i < n; i++) {
s[i] = sc.nextInt();
p[i] = s[i];
}
for (int i = 1; i < n; i++) {
Arrays.sort(p, 0, i);
int temp = 0;
for (int j = 0; j < i; j++) {
temp = p[j] + x;
if (j == i-1)
break;
else {
if (p[j+1] - temp >= x)
break;
}
}
s[i] = Math.max(temp, s[i]);
p[i] = s[i];
}
for (int i = 0; i < n; i++)
System.out.print(s[i] + " ");
}
}