有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 <cstdio>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
int main()
{
int n;
scanf("%d",&n);
stack <LL> s;
LL a[100100];
int num=0;
for(int i=1;i<=n;i++)
{
int t;
scanf("%lld %d",&a[i],&t);
if(t==0&&s.empty())
num++;
if(t==1)
{
s.push(a[i]);
num++;
}
else
{
while(!s.empty())
{
LL tt=s.top();
s.pop();
num--;
if(tt<a[i]&&!s.empty())
continue;
else if(tt<a[i]&&s.empty())
num++;
else
{
s.push(tt);
num++;
break;
}
}
}
}
printf("%d\n",num);
return 0;
}