有一个长度为N的序列。一开始,这个序列是1, 2, 3,... n - 1, n的一个排列。
对这个序列,可以进行如下的操作:
每次选择序列中k个连续的数字,然后用这k个数字中最小的数字替换这k个数字中的每个数字。
我们希望进行了若干次操作后,序列中的每个数字都相等。请你找出需要操作的最少次数。
有一个长度为N的序列。一开始,这个序列是1, 2, 3,... n - 1, n的一个排列。
对这个序列,可以进行如下的操作:
每次选择序列中k个连续的数字,然后用这k个数字中最小的数字替换这k个数字中的每个数字。
我们希望进行了若干次操作后,序列中的每个数字都相等。请你找出需要操作的最少次数。
第一行:两个数字n, k,含义如题,满足2 <= k <= n <= 105;
第二行:n个数字,是1, 2, 3,...n的一个排列。
一个整数,表示最少的次数。
2 2 2 1
1
4 3 1 2 3 4
2
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,k;
while(cin>>n>>k){
for(int i = 0;i<n;i++){
int x;
cin>>x;
}
cout<<ceil((double)(n-1)/(k-1))<<endl;
}
system("pause");
return 0;
}
方法2:考虑极限情况,除了最左边和最右边以外,中间每个相邻的k个公用一个最小值。除去第一个,剩下的n-1个,除(k-1),然后向上取整,就是最少的次数。
答案:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,k;
while(cin>>n>>k){
for(int i = 0;i<n;i++){
int x;
cin>>x;
}
cout<<ceil((double)(n-1)/(k-1))<<endl;
}
system("pause");
return 0;
}
public static void main(String[] args) { int result = 0; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int l = sc.nextInt(); if(n==l){ System.out.println(1); } else{ result = (n-l)/(l-1) +1; if((n-l)%(l-1)>0) { result++; } System.out.println(result); } } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); int count = 1; Integer[] num = new Integer[n]; for(int i = 0; i < n;i++) num[i] = scan.nextInt(); int len = num.length; while(len > k) { len -= (k - 1); count += 1; } System.out.println(count); } }