复试上机----poj 1003坠落的蚂蚁

题目描述 

https://www.nowcoder.com/practice/fdd6698014c340178a8b1f28ea5fadf8?tpId=40&tqId=21420&tPage=5&rp=5&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

    一根长度为1米的木棒上有若干只蚂蚁在爬动。它们的速度为每秒一厘米或静止不动,方向只有两种,向左或者向右。如果两只蚂蚁碰头,则它们立即交换速度并继续爬动。三只蚂蚁碰头,则两边的蚂蚁交换速度,中间的蚂蚁仍然静止。如果它们爬到了木棒的边缘(0或100厘米处)则会从木棒上坠落下去。在某一时刻蚂蚁的位置各不相同且均在整数厘米处(即1,2,3,…99厘米),有且只有一只蚂蚁A速度为0,其他蚂蚁均在向左或向右爬动。给出该时刻木棒上的所有蚂蚁位置和初始速度,找出蚂蚁A从此时刻到坠落所需要的时间。

输入描述:

    第一行包含一个整数表示蚂蚁的个数N(2<=N<=99),之后共有N行,每一行描述一只蚂蚁的初始状态。每个初始状态由两个整数组成,中间用空格隔开,第一个数字表示初始位置厘米数P(1<=P<=99),第二个数字表示初始方向,-1表示向左,1表示向右,0表示静止。

输出描述:

    蚂蚁A从开始到坠落的时间。若不会坠落,输出“Cannot fall!”

示例1

输入

4
10 1
90 0
95 -1
98 -1

输出

复制

98

规律很重要,就像打乒乓球!

#include <iostream>
#include<queue>
#include<vector>
#include<string.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef struct node {
    int pos;
    int dir;
    bool flag;
} node;

static bool cmp(node a,node b)
{
	return a.pos<b.pos;
}

node a[102];
int n;
int main()
{
    cin>>n;
    int posa,indexa;
    for(int i=0; i<n; i++)
    {
        cin>>a[i].pos>>a[i].dir;
        a[i].flag=true;
    }
    sort(a,a+n,cmp);
    for(int i=0; i<n; i++)
    {
        if(a[i].dir==0)
        {
         	posa=a[i].pos;
         	indexa=i;
         	break;
        }   
    }
    int n1=0,n2=0;
    for(int i=indexa-1; i>=0; i--)
    {
        if(a[i].dir==-1)
            a[i].flag=false;
        else
            n1++;
    }

    for(int i=indexa+1; i<n; i++)
    {
        if(a[i].dir==1)
            a[i].flag=false;
        else
            n2++;
    }
    int count=0;
    int res=0;
    if(n1==n2) cout<<"Cannot fall!"<<endl;
    else
    {
        if(n1>n2)
            for(int i=indexa-1; i>=0; i--)
            {
                if(a[i].flag)
                    count++;
                if(count==n2+1) //这里差点搞错了
                {
                    res=100-a[i].pos;
                    break;
                }
            }
        else
            for(int i=indexa+1; i<n; i++)
            {
                if(a[i].flag)
                    count++;
                if(count==n1+1)
                {
                    res=a[i].pos;
                    break;
                }
            }
        cout<<res<<endl;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章