每日一题(3)51nod1289 大鱼吃小鱼

  1. 有N条鱼每条鱼的位置及大小均不同,他们沿着X轴游动,有的向左,有的向右。游动的速度是一样的,两条鱼相遇大鱼会吃掉小鱼。从左到右给出每条鱼的大小和游动的方向(0表示向左,1表示向右)。问足够长的时间之后,能剩下多少条鱼?  
  2. Input  
  3. 第1行:1个数N,表示鱼的数量(1 <= N <= 100000)。  
  4. 第2 - N + 1行:每行两个数A[i], B[i],中间用空格分隔,分别表示鱼的大小及游动的方向(1 <= A[i] <= 10^9,B[i] = 0 或 1,0表示向左,1表示向右)。  
  5. Output  
  6. 输出1个数,表示最终剩下的鱼的数量。  
  7. Input示例  
  8. 5  
  9. 4 0  
  10. 3 1  
  11. 2 0  
  12. 1 0  
  13. 5 0  
  14. Output示例  
  15. 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;
}

猜你喜欢

转载自blog.csdn.net/qq_40911499/article/details/79918749
今日推荐