等差数列
原题链接
问题描述
解题思路
对输入的数据进行排序,找出最小的差值即为这个数列的公差。(注意公差可能为 0)
等差数列求项数(末项 - 首项) / 公差 + 1
参考代码
import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int N = (int)1e5 + 10, n;
static int[] a = new int[N];
public static void main(String[] args) throws Exception {
n = Integer.parseInt(in.readLine());
String[] s = in.readLine().split(" ");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(s[i]);
}
Arrays.sort(a, 0, n);
long mn = a[0], mx = a[n - 1], d = mx - mn;
if (d == 0) {
out.println(n);
} else {
for (int i = 1; i < n; i++) {
d = Math.min(d, a[i] - a[i - 1]);
}
out.println((mx - mn) / d + 1);
}
out.flush();
in.close();
}
}
波动数列
原题链接
问题描述
解题思路
- 状态定义:定义
f[i][j]
为前 i 次操作后数列和为 j 的方案数 - 初始化:
f[0][0] = 1
- 状态转移:设
f[i][j]
为当前状态,那么上一个状态可以是当前状态-a
或者+b
得到,具体-a/+b
的项数和当前的 i 有关。
f[i][j] = f[i - 1][j - i * a] + f[i - 1][j + i * b]
取模后得到f[i][j] = (f[i - 1][(j - i * a) % n] + f[i - 1][(j + i * b) % n]) % MOD
- 得到最终的答案需要
n - 1
次操作
由于 Python 对正负数取模都是正数,Java 则不是,为了防止下标为负数,需要进行双重取模:(x % n + n) % n
参考代码
import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int MOD = (int)1e8 + 7;
static int N = 1010, n, s, a, b;
static int[][] f = new int[N][N];
public static int getMOD(int x) {
return (x % n + n) % n;
}
public static void main(String[] args) throws Exception {
String[] ss = in.readLine().split(" ");
n = Integer.parseInt(ss[0]);
s = Integer.parseInt(ss[1]);
a = Integer.parseInt(ss[2]);
b = Integer.parseInt(ss[3]);
f[0][0] = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
f[i][j] = (f[i - 1][getMOD(j + i * b)] + f[i - 1][getMOD(j - i * a)]) % MOD;
}
}
out.println(f[n - 1][getMOD(s)]);
out.flush();
in.close();
}
}