2023.7.7集训复盘
A.
The Man who became a God
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Kars is tired and resentful of the narrow mindset of his village since they are content with staying where they are and are not trying to become the perfect life form. Being a top-notch inventor, Kars wishes to enhance his body and become the perfect life form. Unfortunately, n
of the villagers have become suspicious of his ideas. The i
-th villager has a suspicion of ai
on him. Individually each villager is scared of Kars, so they form into groups to be more powerful.
The power of the group of villagers from l
to r
be defined as f(l,r)
where
f(l,r)=|al−al+1|+|al+1−al+2|+…+|ar−1−ar|.
Here |x−y|
is the absolute value of x−y
. A group with only one villager has a power of 0
.
Kars wants to break the villagers into exactly k
contiguous subgroups so that the sum of their power is minimized. Formally, he must find k−1
positive integers 1≤r1<r2<…<rk−1<n
such that f(1,r1)+f(r1+1,r2)+…+f(rk−1+1,n)
is minimised. Help Kars in finding the minimum value of f(1,r1)+f(r1+1,r2)+…+f(rk−1+1,n)
.
Input
The first line contains a single integer t
(1≤t≤100)
— the number of test cases. The description of test cases follows.
The first line of each test case contains two integers n,k
(1≤k≤n≤100)
— the number of villagers and the number of groups they must be split into.
The second line of each test case contains n
integers a1,a2,…,an
(1≤ai≤500)
— the suspicion of each of the villagers.
Output
For each test case, output a single integer — the minimum possible value of sum of power of all the groups i. e. the minimum possible value of f(1,r1)+f(r1+1,r2)+…+f(rk−1+1,n)
.
1.把输入的数放入到数组里面
2.建立一个新的数组存放即将用到
3.取后一项减前一项的绝对值
4.把那些数字相加
5.将数组进行全排
6.for(int j=0;j<b-1;j++){
sum-=diff[diff.length-1-j];
}
```java
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for (int i = 0; i < t; i++) {
int n=sc.nextInt();
int k=sc.nextInt();
int sum=0;
int[]arr=new int[n];
for (int i1 = 0; i1 < arr.length; i1++) {
arr[i1]=sc.nextInt();
}
int[]d=new int[n-1];
for (int i1 = 0; i1 < d.length; i1++) {
d[i1]=Math.abs(arr[i1+1]-arr[i1]);
}
Arrays.sort(d);
for (int i1 = 0; i1 < d.length; i1++) {
sum+=d[i1];
}
for (int i1 = 0; i1 <k-1; i1++) {
sum-=d[d.length-1-i1];
}
System.out.println(sum);
}
}
}

浙公网安备 33010602011771号