zoukankan      html  css  js  c++  java
  • 贪心(栈维护,好题)——[Usaco2006 Mar]Mooo

    暴力亦可过,同没意思。。。
    有个O(n)的算法
    从左向右扫
    {
    while{
    if(栈顶元素.h>当前元素.h)   入队,更新栈顶元素对应的牛的V ,结束while循环
    else 出队
    }直到队列为空
    }
    再从右向左
    View Code
    #include<stdio.h>
    #include
    <iostream>
    #include
    <stack>
    using namespace std;
    struct data
    {
    int h,v,no;
    }node[
    50009];
    int all[50009];

    int main()
    {
    int n;
    while(scanf("%d",&n)!=EOF)
    {
    int i;
    for(i=0;i<n;i++)
    {
    scanf(
    "%d%d",&node[i].h,&node[i].v);
    node[i].no
    =i;
    all[i]
    =0;
    }

    stack
    <data>ss;
    ss.push(node[
    0]);
    for(i=1;i<n;i++)//从左到右
    {
    while(!ss.empty())
    {
    if(ss.top().h>node[i].h)
    {
    all[ss.top().no]
    +=node[i].v;
    ss.push(node[i]);
    break;
    }
    ss.pop();
    }
    if(ss.empty())ss.push(node[i]);//若为空入栈
    }

    while(!ss.empty())
    ss.pop();
    ss.push(node[n
    -1]);
    for(i=n-2;i>=0;i--)//从右到左
    {
    while(!ss.empty())
    {
    if(ss.top().h>node[i].h)
    {
    all[ss.top().no]
    +=node[i].v;
    ss.push(node[i]);
    break;
    }
    ss.pop();
    }
    if(ss.empty())ss.push(node[i]);
    }

    int max=0;
    for(i=0;i<n;i++)
    if(max<all[i])
    max
    =all[i];

    printf(
    "%d\n",max);
    }
    }

      

      


    #include<stdio.h>
    #include
    <iostream>
    #include
    <stack>
    using namespace std;
    struct data
    {
    int h,v,no;
    }node[
    50009];
    int all[50009];

    int main()
    {
    int n;
    while(scanf("%d",&n)!=EOF)
    {
    int i;
    for(i=0;i<n;i++)
    {
    scanf(
    "%d%d",&node[i].h,&node[i].v);
    node[i].no
    =i;
    all[i]
    =0;
    }

    stack
    <data>ss;
    ss.push(node[
    0]);
    for(i=1;i<n;i++)//从左到右
    {
    while(!ss.empty())
    {
    if(ss.top().h>node[i].h)
    {
    all[ss.top().no]
    +=node[i].v;
    ss.push(node[i]);
    break;
    }
    ss.pop();
    }
    if(ss.empty())ss.push(node[i]);
    }

    while(!ss.empty())
    ss.pop();
    ss.push(node[n
    -1]);
    for(i=n-2;i>=0;i--)//从右到左
    {
    while(!ss.empty())
    {
    if(ss.top().h>node[i].h)
    {
    all[ss.top().no]
    +=node[i].v;
    ss.push(node[i]);
    break;
    }
    ss.pop();
    }
    if(ss.empty())ss.push(node[i]);
    }

    int max=0;
    for(i=0;i<n;i++)
    if(max<all[i])
    max
    =all[i];

    printf(
    "%d\n",max);
    }
    }

      

  • 相关阅读:
    用Jenkins构建Django持续集成环境
    DACLs and ACEs
    windows共享文件分析
    summary
    Mysql InnoDB行锁实现方式
    网关 整理 fastcgi wsgi
    Git提交代码规范 而且规范的Git提交历史,还可以直接生成项目发版的CHANGELOG(semantic-release)
    松本行弘:代码的未来(图灵访谈)
    “对外部(局部)变量的访问”是C语言函数指针的最大弱点
    CAP解决方案-BASE
  • 原文地址:https://www.cnblogs.com/huhuuu/p/2118839.html
Copyright © 2011-2022 走看看