翻转数列1
简单模拟(超时)
import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
long n,m;
n = sc.nextInt();
m = sc.nextInt();
long sum =0;
long k = 1;
long symbol = 1;
if(m==1)
for(long i=1;i<=n;i++,k++){
if(k==m){symbol*=-1;k=0;}
sum+= (i * symbol);
//System.out.println(i * symbol);
}
else
for(long i=1;i<=n;i++){
if(i%m==1){symbol*=-1;}
sum+= (i * symbol);
//System.out.println(i * symbol);
}
System.out.println(sum);
}
}
找前 n 项和公式
没一个【负,正】为一组,以哦那个有 n/2m 组。开头是负数。
对于其中任意一组有 -x,-(x+1),-(x+2)…-(x+m-1), (x+m),(x+m+1),…,(x+2m-1);
本组各项相加:
原式 = -x+ -(x+1) + … + -(x+m-1) + x+m + x+m+1 + … + x+2m+1
=-x+(x+m) + -(x+1)+(x+1+m) + -(x+2)+(x+2+m) + … + -(x+m-1)+(x+2m-1)
=-m+m+m+…+m ······ 即m个m相加
=(m*m)
=m2
一共有n/2m组,故前n项和
S = m2n/2m = mn/2.
import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
long n,m;
n=sc.nextLong();
m=sc.nextLong();
System.out.println(m*n/2);
}
}
纸牌游戏2
import java.util.*;
public class Main{
static Scanner sc = new Scanner(System.in);
public static void main(String []args){
int n = sc.nextInt();
List<Integer> list = new ArrayList<>();
for(int i=0;i<n;i++){
list.add(sc.nextInt());
}
Collections.sort(list, Collections.reverseOrder());
Integer difference = 0;
Iterator<Integer> it = list.iterator();
while(it.hasNext()){
difference += it.next();
if(it.hasNext()) difference -= it.next();
}
System.out.println(difference);
}
}
小Q的歌单3
主要参考了组合数的方法。4
import java.util.Scanner;
class Solution {
long c[][] = new long[105][105];
final int mod = 1000000007;
void init() {
c[0][0] = 1L;
for (int i = 1; i <= 101; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++)
c[i][j] = (c[i - 1][j] % mod + c[i - 1][j - 1] % mod) % mod;
}
}
long judge(int k, int a, int x, int b, int y) {
long ans = 0;
for (int i = 0; i <= x; i++) {
if ((i * a <= k) && ((k - i * a) % b == 0) && ((k - i * a) / b <= y)) {
ans = (ans + (c[x][i] * c[y][(k - i * a) / b]) % mod) % mod;
}
}
return ans;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k;
int a, b, x, y;
k = sc.nextInt();//歌单总长度
a = sc.nextInt();//第一种长度
x = sc.nextInt();//第一种数量
b = sc.nextInt();//第二种长度
y = sc.nextInt();//第二种书量
Solution solution = new Solution();
solution.init();
System.out.println(solution.judge(k, a, x, b, y));
}
}
用到的取模公式5
(a + b) % p = (a%p + b%p) %p
(a - b) % p = ((a%p - b%p) + p) %p