1289 大鱼吃小鱼

来源:互联网 发布:无锡cnc编程招聘 编辑:程序博客网 时间:2024/05/10 06:51
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示例
54 03 12 01 05 0
Output示例
2
栈模拟求解,注意题目中是不存在 5 0, 5 1这种数据的,即迎面而来的两条鱼的重量是一样的这种数据,如果存在的话则需要做特殊的处理。
#include <cmath>#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <string>#include <vector>#include <queue>#include <stack>#include <algorithm>using namespace std;stack<int> stk;void init() {    while(!stk.empty()) stk.pop();}int main() {        int n;    int x, d;    int ans = 0;    init();    scanf("%d", &n);    for(int i = 0; i < n; ++i) {        scanf("%d %d", &x, &d);        if(stk.empty() && d == 0) {            ans++;            continue;        }        if(d == 1) {            stk.push(x);            continue;        }        while(!stk.empty()) {            int top = stk.top();            if(top > x) {                break;            } else {                stk.pop();            }        }        if(stk.empty()) ans++;    }    cout << ans + stk.size() << endl;    return 0;}


0 0
原创粉丝点击