RMQ+递归;
# include <stdio.h>
![](/Images/OutliningIndicators/None.gif)
# define N 50005
# define L 16
![](/Images/OutliningIndicators/None.gif)
int n, a[N], mn[N][L], mx[N][L];
int ans;
![](/Images/OutliningIndicators/None.gif)
int Max_t(int x, int y)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
return a[x] > a[y] ? x : y;
}
![](/Images/OutliningIndicators/None.gif)
int Min_t(int x, int y)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
return a[x] < a[y] ? x : y;
}
![](/Images/OutliningIndicators/None.gif)
void init(void)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
int i;
ans = -1;
for (i = 1; i <= n; ++i)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
scanf("%d", &a[i]);
mn[i][0] = i;
mx[i][0] = i;
}
}
![](/Images/OutliningIndicators/None.gif)
void pre(void)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
int l, j, i;
for (j = 1, l = 1; l*2 <= n; ++j, l*=2)
for (i = 1; i+2*l <= n+1; ++i)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
mn[i][j] = Min_t(mn[i][j-1], mn[i+l][j-1]);
mx[i][j] = Max_t(mx[i][j-1], mx[i+l][j-1]);
}
}
![](/Images/OutliningIndicators/None.gif)
int rmq(int x, int y, int bj)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
int j = 0, l = 1;
while (2*l <= y-x+1) l*=2, ++j;
if (bj < 0) return Min_t(mn[x][j], mn[y-l+1][j]);
else return Max_t(mx[x][j], mx[y-l+1][j]);
}
![](/Images/OutliningIndicators/None.gif)
void cal(int s, int t)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
int x, y;
if (s >= t) return ;
x = rmq(s, t, -1);
y = rmq(s, t, 1);
if (x == y) return ;
if (x < y)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
ans = y-x>ans ? y-x:ans;
if (s < x) cal(s, x-1);
if (y < t) cal(y+1, t);
}
else
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (s < y) cal(s, y);
cal(y+1, x-1);
if (x < t) cal(x, t);
}
}
![](/Images/OutliningIndicators/None.gif)
int main()
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
//freopen("test.in", "r", stdin);
//freopen("test.out", "w", stdout);
![](/Images/OutliningIndicators/InBlock.gif)
while (~scanf("%d", &n))
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
init();
pre();
cal(1, n);
printf("%d\n", ans);
}
![](/Images/OutliningIndicators/InBlock.gif)
return 0;
}
![](/Images/OutliningIndicators/None.gif)
posted on 2012-08-27 09:43
yajunw 阅读(139)
评论(0) 编辑 收藏 引用