第十四届蓝桥杯三月真题刷题训练——第 14 天

等差数列

原题链接

等差数列

问题描述

todo:这里复制题目描述

解题思路

对输入的数据进行排序,找出最小的差值即为这个数列的公差。(注意公差可能为 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();
    }  
}

波动数列

原题链接

波动数列

问题描述

todo:这里复制题目描述

解题思路

参考题解

  • 状态定义:定义 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();
    }  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值