本文主要是介绍题目 1168: 简单计算,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
有一个n+2个元素a[0], a[1], ..., a[n+1] (n <= 3000, -1000 <= a[i] <=1000)构成的数列.
已知对i=1, 2, ..., n有a[i] = (a[i-1] + a[i+1])/2 - c[i].
给定a0, a[n+1], c[1], ... , c[n]. 写一个程序计算a[1].
解题思路:
2 * a[1] = a[0] + a[2] - 2 * c[1]
2 * a[2] = a[1] + a[3] - 2 * c[2]
.......
2 * a[n-1] = a[n-2] + a[n] - 2 * c[n-1]
2 * a[n] = a[n-1] + a[n+1] - 2 * c[n]
左边所有项相加等于右边所有项相加, 消除后即可得到:a[1] + a[n] = a[0] + a[n+1] - 2*sum(c{1..n})
a[n] = a[0] + a[n+1] - 2*sum(c{1..n}) - a[1]
同理: a[n-1] = a[0] + a[n] - 2*sum(c{1..n-1}) - a[1]
.......
a[2] = a[0] + a[3] - 2*sum(c{1..2}) - a[1]
a[1] = a[0] + a[2] - 2*sum(c{1..1}) - a[1]
左边所有项相加等于右边所有项相加, 消除后即可得到最后的解:
a[1] = (n * a[0] + a[n+1] - 2*(sum(c{1..1}) + sum(c{1..2}) + .... + sum(c{1..n})))/(n+1)
代码:
package lanqiao;import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){int n = sc.nextInt();double start = sc.nextDouble(), end = sc.nextDouble();double[] c = new double[n+1];for(int i = 1; i <= n; i++)c[i] = sc.nextDouble();double sum = 0;for(int i = 1; i <= n; i++){for(int j = 1; j <= i; j++){sum += c[j];}}System.out.printf("%.2f\n", (n*start + end - 2*sum) / (n+1));}sc.close();}
}
这篇关于题目 1168: 简单计算的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!