zoukankan      html  css  js  c++  java
  • [ACM]Shopping

    题目描述

    Saya and Kudo go shopping together.
    You can assume the street as a straight line, while the shops are some points on the line.
    They park their car at the leftmost shop, visit all the shops from left to right, and go back to their car.
    Your task is to calculate the length of their route.

    输入

    The input consists of several test cases.
    The first line of input in each test case contains one integer N (0<N<100001), represents the number of shops.
    The next line contains N integers, describing the situation of the shops. You can assume that the situations of the shops are non-negative integer and smaller than 2^30.
    The last case is followed by a line containing one zero.

    输出

     For each test case, print the length of their shopping route.

    示例输入

    4
    24 13 89 37
    6
    7 30 41 14 39 42
    0

    示例输出

    152
    70

    提示

    Explanation for the first sample: They park their car at shop 13; go to shop 24, 37 and 89 and finally return to shop 13. The total length is (24-13) + (37-24) + (89-37) + (89-13) = 152


    解题思路:一开始没有多想算法,第一反应就是先排序,再把排序(从小到大)后的几个距离数值放在数组a[]中,然后用一个循环 sum+=( a[j+1]-a[j] ),最后再加上 最大距离 -  最小距离 ,输出最终sum,结果提交超时。后来又想了想算法,发现 原来sum+=( a[j+1]-a[j] )的结果和 最大距离与最小距离的差相等,因此本题不需要排序,只要找出数组中最小的数min,和最大的数max 即可, 用公式 sum=2*(max-min),输出sum就可以了,问题通过。本题再次证明了算法的重要性。 Ps:本题里的提示部分是个陷阱啊!

    代码:

    #include <iostream>
    using namespace std;
    int main()
    {
    
        int N,i;
        while(cin>>N&&N!=0)
        {
            int a[100001],min,max;
            for(i=1;i<=N;i++)
                cin>>a[i];
                min=a[1];
                max=a[1];
            for(i=2;i<=N;i++)
            {
                if(a[i]>max)
                    max=a[i];
                if(a[i]<min)
                    min=a[i];
            }
            int sum=0;
            sum=2*(max-min);//最重要的一步
            cout<<sum<<endl;
        }
        return 0;
    }
    


    运行截图:




  • 相关阅读:
    共相式GIS
    Windows下启动停止Oracle11g服务-为解决系统变慢而生
    myeclipse同时部署两个项目-permgen space
    解决“System.Data.OracleClient需要Oracle客户端软件8.1.7或更高版本”
    MyEclipse Servers视窗出现“Could not create the view: An unexpected exception was thrown”错误解决办法
    C++11多线程std::thread的简单使用
    STL中的set使用方法详细
    Cocos2dx使用网络图片
    Cocos2d-x 截图功能
    GitHub使用指南之快速入门
  • 原文地址:https://www.cnblogs.com/sr1993/p/3697867.html
Copyright © 2011-2022 走看看