CodeForces 567A Lineland Mail 贪心

原题: http://codeforces.com/contest/567/problem/A
题目: Lineland Mail
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).
Strange but true, the cost of sending the letter is exactly equal to the distance between the sender’s city and the recipient’s city.
For each city calculate two values ??mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city
Input
The first line of the input contains integer n (2?≤?n?≤?105) — the number of cities in Lineland. The second line contains the sequence of n distinct integers x1,?x2,?…,?xn (?-?109?≤?xi?≤?109), where xi is the x-coordinate of the i-th city. All the xi’s are distinct and follow in ascending order.
【CodeForces 567A Lineland Mail 贪心】Output
Print n lines, the i-th line must contain two integers mini,?maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city.
Sample test(s)
input
4
-5 -2 2 7
output
3 12
3 9
4 7
5 12
input
2
-1 1
output
2 2
2 2
思路: 对于给定的一个升序列,求出每个点与其他点差值(绝对值)的最大值和最小值。
除了边界点的最大差只能与另一个边界点做差,最小值只能和单边做差,其他的只都需要和边界点做差就能求出最值。
代码:

#include #include"string.h" #include"cstdio" #include"stdlib.h" #include"algorithm"using namespace std; typedef __int64 lint; const int N = 100005; lint n; lint a[N]; lint maxans[N]; lint minans[N]; int main() { while(scanf("%I64d",&n)!=EOF) { memset(a,0,sizeof(a)); memset(maxans,0,sizeof(maxans)); memset(minans,0,sizeof(minans)); for(lint i=1; i<=n; i++) { scanf("%I64d",&a[i]); } maxans[1]=a[n]-a[1]; minans[1]=a[2]-a[1]; for(lint i=2; i<=n-1; i++) { maxans[i]=max(a[i]-a[1],a[n]-a[i]); minans[i]=min(a[i+1]-a[i],a[i]-a[i-1]); } maxans[n]=a[n]-a[1]; minans[n]=a[n]-a[n-1]; for(lint i=1; i<=n; i++) { printf("%I64d %I64d\n",minans[i],maxans[i]); } } return 0; }

    推荐阅读