基础RMQ模板
dp[i][j]代表从i开始并且包括i的2^j个数字中最小(最大)的值。
构建的过程可以用动态规划完成
dp[i][j]=min(dp[i][j-1],dp[i+(1<<j-1)][j-1])
void rmq_init()
{
for(int i=1;i<=N;i++) dp[i][0]=arr[i];
for(int j=1;(1<<j)<=N;j++)
for(int i=1;i+(1<<j)-1<=N;i++)
dp[i][j]=min(dp[i][j-1],dp[i+(1<<j-1)][j-1]);
}
int query(int l,int r)
{
int k=log2(r-l+1);
return min(dp[l][k],dp[r-(1<<k)+1][k]);
}
从一个数字中删去若干位,要求结果最小。
178543 4,从178543中删去4位,最小结果是13。
Sample Input
178543 4
1000001 1
100001 2
12345 2
54321 2
Sample Output
13
1
0
123
321
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 1024;
int n, m;
char s[maxn], ans[maxn];
int dp[maxn][10];
void rmq_init() {
for (int i = 1; i <= n; ++i) dp[i][0] = i;
for (int j = 1; (1 << j) <= n; ++j)
for (int i = 1; i + (1 << j) - 1 <= n; ++i) {
dp[i][j] = s[dp[i][j - 1] - 1] <= s[dp[i + (1 << (j - 1))][j - 1] - 1] ? dp[i][j-1] :
dp[i + (1 << (j - 1))][j-1];
}
}
int query(int x, int y) {
int k = log2(y - x + 1);
return s[dp[x][k] - 1] <= s[dp[y - (1 << k) + 1][k] - 1] ? dp[x][k] : dp[y - (1 << k) + 1][k];
}
int main()
{
while (scanf("%s%d", s, &m)!=EOF) {
int k = 1, need, i = 0;
n = strlen(s);
rmq_init();
need = n - m + 1;
while (--need) {
k = query(k, n - need + 1);
ans[i] = s[k - 1];
++i, ++k;
}
for (k = 0; k < i && ans[k] == '0'; ++k);
if (i == k) printf("0\n");
else {
for (; k < i; k++) printf("%c", ans[k]);
printf("\n");
}
}
return 0;
}