codeforces 496A. Minimum Difficulty 解题报告

题目链接:http://codeforces.com/contest/496/problem/A

题目意思:给出有 n 个数的序列,然后通过删除除了第一个数和最后一个数的任意一个位置的数,求出删除这个数之后序列的最大相邻差是多少,然后删除下一个数,继续求出最大相邻差,直到删到倒数第二个数,最后从这些最大相邻差中找出最小的那个输出。例如:有序列为1 2 3 7 8,删除第二个、第三个、第四个数后得到的序列分别为:(1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8)。那么最大相邻差分别为 4,5,5,选出最小的那个就是答案 4 。

  是由于bc不会做,临时走来做 virtual 的,效果当然不是太好。。。

  可以这样想,两重循环(外循环 i ,内循环j),i 表示当前需要删除第 i 个数,j 用来删除第 i 个数之后的序列中,最大相邻差。一种很简单的办法是,

      if 【i == j】   d = a[j+1] - a[i-1]

  else     d = a[j+1] - a[j]

  else 语句用得比较巧妙,例如对于 1 2 3 7 8 这个序列,如果当前删除的是3,那么序列就变成 1 2 7 8。当算到 7 这个数的时候, d = 7 - 3,虽然这个 d 并不存在(3 没有了嘛),但是算了根本不会影响结果,因为 7 - 3 绝对比 7 - 2 小!

  

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 const int maxn = 100 + 5;
 9 const int INF = 1000 + 5;
10 int a[maxn];
11 
12 int main()
13 {
14     #ifndef ONLINE_JUDGE
15         freopen("in.txt", "r", stdin);
16     #endif // ONLINE_JUDGE
17 
18     int n;
19     while (scanf("%d", &n) != EOF)
20     {
21         for (int i = 1; i <= n; i++)
22             scanf("%d", &a[i]);
23         int minans = INF;
24         for (int i = 2; i <= n-1; i++)
25         {
26             int maxans = -INF;
27             for (int j = 1; j <= n-1; j++)
28             {
29                 if (i == j)
30                     maxans = max(maxans, a[j+1] - a[i-1]);
31                 else
32                     maxans = max(maxans, a[j+1] - a[j]);
33             }
34             minans = min(minans, maxans);
35         }
36         printf("%d
", minans);
37     }
38     return 0;
39 }

原文地址:https://www.cnblogs.com/windysai/p/4175956.html