传送门:http://poj.org/problem?id=2601
Description
There is a sequence of n+2 elements a0, a1, …, an+1(n <= 3000, -1000 <= ai <=1000). It is known that ai = (ai-1 + ai+1)/2 - ci for each i=1, 2, …, n.
You are given a0, an+1, c1, … , cn. Write a program which calculates a1.
Input
The first line of an input contains an integer n. The next two lines consist of numbers a0 and an+1 each having two digits after decimal point, and the next n lines contain numbers ci (also with two digits after decimal point), one number per line.
Output
The output file should contain a1 in the same format as a0 and an+1.
Sample Input
1
50.50
25.50
10.15
Sample Output
27.85
一开始没读懂题意,后来仔细一看,原来就是给一个递推关系式,来求a1
由2ai = ai–1 + ai+1 – 2ci,将i = 1,2,3,4……n带入,得:
2a1 = a0 + a2 - 2c1
2a2 = a1 + a3 - 2c2
2a3 = a2 + a4 - 2c3
…… …… ……
2an = an-1 + an+1 - 2cn,
然后保留第一个式子i, 并从第一个式子往下加,又得到n个式子:
2a1 = a0 + a2 - 2c1
a1 + a2 = a0 + a3 - 2(c1 + c2)
a1 + a3 = a0 + a4 - 2(c1 + c2 + c3)
…… …… …… ……
a1 + an = a0 + an+1 - 2(c1 + c2 + c3 + …… + cn)
n个式子相加,得:
(n + 1)a1 = na0 + an+1 - 2(nc1 + (n-1)c2 + (n-2)c3 + …… + cn),便可求出答案
程序代码:
#include<cstdio>
#include <iostream>
#include<algorithm>
#include <string.h>
#define N 3010
using namespace std;
double a[N], c[N];
int main()
{
#ifndef ONLINE_JUDGE
freopen("1.txt", "r", stdin);
#endif
int n, i, j;
double sum;
while(~scanf("%d", &n))
{
sum = 0.0;
cin >> a[0] >> a[n+1];
sum = n * a[0] + a[n + 1];
for (i = 0; i < n; i++)
{
cin >> c[i];
sum -= 2 * (n - i) * c[i];
}
printf("%.2lf\n", sum/(n+1));
}
return 0;
}