zoukankan      html  css  js  c++  java
  • poj1852

    Ants
    Time Limit: 1000MS   Memory Limit: 30000K
    Total Submissions: 21604   Accepted: 8858

    Description

    An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn back and start walking in opposite directions. We know the original positions of ants on the pole, unfortunately, we do not know the directions in which the ants are walking. Your task is to compute the earliest and the latest possible times needed for all ants to fall off the pole.

    Input

    The first line of input contains one integer giving the number of cases that follow. The data for each case start with two integer numbers: the length of the pole (in cm) and n, the number of ants residing on the pole. These two numbers are followed by n integers giving the position of each ant on the pole as the distance measured from the left end of the pole, in no particular order. All input integers are not bigger than 1000000 and they are separated by whitespace.

    Output

    For each case of input, output two numbers separated by a single space. The first number is the earliest possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately) and the second number is the latest possible such time. 
    分析:
    题目大意就是一根杆子上有很多只蚂蚁,每一只蚂蚁的朝向不同,当一只蚂蚁走到杆子的端点时,蚂蚁从杆子上掉落,当两只蚂蚁相遇时,会各自折返回去。问所有蚂蚁从杆子上掉落所需要的最短时间和最长时间
    先考虑最短时间,当所有蚂蚁朝向离端点近的方向时,所有时间里的最大时间即为所有蚂蚁掉落所需要的时间。
    再来考虑最长时间,我们假设俩只蚂蚁相遇,那么相遇之后各自返回端点,其实可以看成蚂蚁不换方向,继续前进,取两者中的较大值,再寻找所有值中的最大值即可。
    代码如下:
    #include<iostream>
    using namespace std;
    int L,ants;
    const int max_n=100000;
    int x[max_n];
    void solve(int x[],int ants)
    {
        int i,mintime=0;
        for(i=0;i<ants;i++)
            mintime=max(mintime,min(x[i],L-x[i]));
            int maxtime=0;
        for(i=0;i<ants;i++)
        {
            maxtime=max(maxtime,max(x[i],L-x[i]));
        }
    cout<<mintime<<" "<<maxtime<<endl;
    }
    
    //using namespace std;
    int main()
    {
        int t;
        cin>>t;
    while(t--)
    {
        cin>>L>>ants;
        int i,min1,max1;
        for(i=0;i<ants;i++)
            cin>>x[i];
        solve(x,ants);
    }
    
    
    
    
    
    
        return 0;
    }
  • 相关阅读:
    剑指Offer-二叉搜索树与双向链表
    剑指Offer-数组中只出现一次的数字
    剑指Offer-栈的压入、弹出序列
    剑指Offer-反转链表
    剑指Offer-和为S的两个数字
    剑指Offer-数字在排序数组中出现的次数
    剑指Offer-二叉树的下一个结点
    Notepad++中实现Markdown语法高亮与实时预览
    centos7安装activemq5.15
    博客园展示音频视频
  • 原文地址:https://www.cnblogs.com/renxin123/p/8448105.html
Copyright © 2011-2022 走看看