1047. Simple Calculations
Time Limit: 1.0 second
Memory Limit: 16 MB
Memory Limit: 16 MB
There is a sequence of N + 2 elements a0, a1,
…, aN+1 (1 ≤ N ≤ 3000, −2000 ≤ ai ≤ 2000). 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 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
Output a1 in the same format as a0 and aN+1.
Sample
input | output |
---|---|
1 50.50 25.50 10.15 |
27.85 |
根据原式可以得
a[n+1]-a[n]=a[n]-a[n-1]+2*c[n]①
设S[n]=c[1]+c[2]+…+c[n]
对①式叠加相消可以得到a[n+1]-a[1]=a[n]-a[0]+2*S[n]
整理得a[n+1]-a[n]=a[1]-a[0]+2*S[n]②
对②式叠加相消可得到a[n+1]-a[1]=n*(a[1]-a[0])+2*(S[1]+S[2]+…+S[n])
#include <iostream>
using namespace std;
int main()
{
int i, n;
double a_0, a_n1, a_1, c[3000], s = 0, temp = 0;
cin>>n>>a_0>>a_n1;
for (i=0; i<n; i++)
cin>>c[i];
for (i=0; i<n; i++)
{
temp += c[i];
s += temp;
}
a_1 = (a_n1 + n * a_0 - 2 * s) / (n + 1);
printf("%.2f\n", a_1);
}