51NOD - 1289 大鱼吃小鱼 (栈)

版权声明:欢迎转载 https://blog.csdn.net/l18339702017/article/details/83148356

1289 大鱼吃小鱼 

题目来源: Codility

基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题

 收藏

 关注

有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
扫描二维码关注公众号,回复: 3625811 查看本文章

一个非常有意思的题目,用栈来模拟一下即可

#pragma GCC optimize(2)
#include <bits/stdc++.h>
using namespace std;
#define clr(a) memset(a,0,sizeof(a))
#define line cout<<"-----------------"<<endl;

typedef long long ll;
const int maxn = 1e5+10;
const int MAXN = 1e6+10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int N = 1010;

int n;
stack<int> s;

int main(){
	scanf("%d", &n);
	int ans = n;
	for(int i = 0; i < n; i++){
		int x, y;
		scanf("%d%d", &x, &y);
		if(y == 1) s.push(x);
		else{
			while(!s.empty()){
				if(s.top() < x){
					s.pop();
					ans --;
				}
				else{
					ans --;
					break;
				}
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/l18339702017/article/details/83148356
今日推荐