zoukankan      html  css  js  c++  java
  • uva 11078 Open Credit System

    https://vjudge.net/problem/UVA-11078

    题意:

    给出一个整数序列,要求找出两个位置i,j(i < j),Ai - Aj的值最大,并且输出这个最大值。

    思路:

    原来我考虑的是一边遍历,一边排序,求Aj - Ai的最小值,然后总的复杂度是O(NlogN),但是没有想到这样都tle了,贴上代码警示。

     1 #include <stdio.h>
     2 #include <algorithm>
     3 using namespace std;
     4 
     5 int a[100005];
     6 
     7 int main()
     8 {
     9     int t;
    10 
    11     scanf("%d",&t);
    12 
    13     while(t--)
    14     {
    15         int n;
    16 
    17         scanf("%d",&n);
    18 
    19         int ans = 100000000;
    20 
    21         for (int i = 1;i <= n;i++)
    22         {
    23             scanf("%d",&a[i]);
    24         }
    25 
    26         //int maxn = a[1];
    27 
    28         for (int i = 2;i <= n;i++)
    29         {
    30             sort(a+1,a+i);
    31 
    32             ans = min(ans,a[i] - a[i-1]);
    33         }
    34 
    35         printf("%d
    ",-ans);
    36     }
    37 
    38     return 0;
    39 }

    后来呢,那么这个都过不了,只有用线性的时间喽,所以就动态更新这个坐标之前的最大值,那么最大值肯定是某个坐标前面的最大值静减去当前值,所以就可以O(N)得出答案。

    代码:

     1 #include <stdio.h>
     2 #include <algorithm>
     3 using namespace std;
     4 
     5 int a[100005];
     6 
     7 int main()
     8 {
     9     int t;
    10 
    11     scanf("%d",&t);
    12 
    13     while(t--)
    14     {
    15         int n;
    16 
    17         scanf("%d",&n);
    18 
    19         int ans = -100000000;
    20 
    21         for (int i = 1;i <= n;i++)
    22         {
    23             scanf("%d",&a[i]);
    24         }
    25 
    26         int maxn = a[1];
    27 
    28         for (int i = 2;i <= n;i++)
    29         {
    30             ans = max(maxn - a[i],ans);
    31 
    32             maxn = max(a[i],maxn);
    33         }
    34 
    35         printf("%d
    ",ans);
    36     }
    37 
    38     return 0;
    39 }
  • 相关阅读:
    如何启用apache的gzip压缩?
    Zend Framework配置Nginx的rewrite
    数据库差异比较工具
    心愿王泽 杨颖 乔媛 唐景莲
    在所有存储过程中查找一个关键字
    通用分页存储过程
    JavaScript开发工具 Aptana
    js如何控制select控件(下拉列表)
    Read and write flat file
    Extreme Programming
  • 原文地址:https://www.cnblogs.com/kickit/p/7620016.html
Copyright © 2011-2022 走看看