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);
    }
    }

      

  • 相关阅读:
    字符数组与指针
    终于在博客园安家了
    关于SET NOCOUNT
    如何判断请求是否发送成功以及获取请求中的数据
    mysql进阶 withas 性能调优
    Linux mkdir
    Linux umask and chmod
    C linux Debug
    Linux sed
    Linux ulimit
  • 原文地址:https://www.cnblogs.com/huhuuu/p/2118839.html
Copyright © 2011-2022 走看看