雕刻时光

just do it……nothing impossible
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

贪心(栈维护,好题)——[Usaco2006 Mar]Mooo

Posted on 2011-07-27 21:31  huhuuu  阅读(361)  评论(0编辑  收藏  举报
暴力亦可过,同没意思。。。
有个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);
}
}