- 有N条鱼每条鱼的位置及大小均不同,他们沿着X轴游动,有的向左,有的向右。游动的速度是一样的,两条鱼相遇大鱼会吃掉小鱼。从左到右给出每条鱼的大小和游动的方向(0表示向左,1表示向右)。问足够长的时间之后,能剩下多少条鱼?
- Input
- 第1行:1个数N,表示鱼的数量(1 <= N <= 100000)。
- 第2 - N + 1行:每行两个数A[i], B[i],中间用空格分隔,分别表示鱼的大小及游动的方向(1 <= A[i] <= 10^9,B[i] = 0 或 1,0表示向左,1表示向右)。
- Output
- 输出1个数,表示最终剩下的鱼的数量。
- Input示例
- 5
- 4 0
- 3 1
- 2 0
- 1 0
- 5 0
- Output示例
- 2
思路:运用栈,以右边的入栈,遇到左边的就和栈里面的比较,知道吃不了为止。
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
stack<int>fisher;
struct fish
{
int a,b;
}yu[100005];
int main()
{
int n,ans=0;
cin>>n;
ans=n;
for (int i=0;i<n;i++)
{
cin>>yu[i].a>>yu[i].b;
if (yu[i].b==1)
fisher.push(yu[i].a);//入栈
else
{
while (!fisher.empty())
{
if (yu[i].a>fisher.top())
{
fisher.pop();
ans--;//能吃掉,出栈并且数量减少
}
else
{
ans--;//被吃掉,数量减少
break;
}
}
}
}
cout<<ans<<endl;
return 0;
}