// Code By CloudySky #include<bits/stdc++.h> // #define int long long namespace IO // namespace IO usingnamespace IO; constint inf = 2e9; constint Maxn = 3e5 + 10; usingnamespace std;
int a[Maxn], lg[Maxn], St[Maxn][30], Min, x;
voidSt_init(int n){ lg[1] = 0; for (int i = 2; i <= n; ++i) lg[i] = lg[i >> 1] + 1; for (int i = 1; i <= n; ++i) St[i][0] = a[i]; for (int ln = 1; ln <= lg[n]; ++ln) { for (int l = 1; l + (1 << ln) - 1 <= n; ++l) St[l][ln] = min(St[l][ln - 1], St[l + (1 << (ln - 1))][ln - 1]); } }
intquery(int l, int r){ int k = lg[(r - l + 1)]; returnmin(St[l][k], St[r - (1 << k) + 1][k]); }
int stc[Maxn], top;
signedmain(){ int n = read(), m = read(); for (int i = 1; i <= n; ++i) a[i] = read(); St_init(n); // 特殊处理前 m 个数。 Min = query(1, m), x; for (int i = 1; i <= m; ++i) { if (a[i] == Min) { x = i; break; } stc[++top] = a[i]; } print(a[x], ' '); // 遍历序列,贪心 for (int r = m + 1; r <= n; ++r) { Min = query(x + 1, r); // 求得最小值 while (top && stc[top] <= Min) // 和栈顶比较 print(stc[top--], ' '); // 弹栈 else for (x = x + 1; x <= r; ++x) { // 将 [l, x - 1] 加入栈中,同时找到 x if (a[x] == Min) { print(a[x], ' '); break; } stc[++top] = a[x]; } } // 特殊处理后 m 个数。这里 i 只是单纯的枚举次数,不再有其他含义。 for (int i = 1; i <= m - 1; ++i) { Min = inf; if (x + 1 <= n) Min = query(x + 1, n); while (top && stc[top] <= Min) print(stc[top--], ' '); else for (x = x + 1; x <= n; ++x) { if (a[x] == Min) { print(a[x], ' '); break; } stc[++top] = a[x]; } } return0; }
// Code By CloudySky #include<bits/stdc++.h> #define int long long #define inf 0x3f3f3f3f3f3f3f3f namespace IO { inlineintread(){ int x = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + (c ^ 48); c = getchar(); } return x * f; } voidprint_n(int x){ if (x > 9) print_n(x / 10); putchar(x % 10 + '0'); } inlinevoidprint(int x, char s = '\n'){ if (x < 0) putchar('-'), x = -x; print_n(x), putchar(s); } } // namespace IO usingnamespace IO; constint Maxn = 1e3 + 10; usingnamespace std;
int a[Maxn], f[Maxn][Maxn][2];
signedmain(){ int n = read (), p = read (); for (int l = 1; l <= n + 1; ++l) { for (int r = 1; r <= n + 1; ++r) { f[l][r][0] = f[l][r][1] = inf; } } for (int i = 1; i <= n; ++i) a[i] = read (); a[n + 1] = p; sort (a + 1, a + n + 2); n = unique (a + 1, a + n + 2) - a - 1; p = lower_bound (a + 1, a + n + n, p) - a; f[p][p][0] = f[p][p][1] = 0; for (int len = 2; len <= n; ++len) { for (int l = 1; l + len - 1 <= n; ++l) { int r = l + len - 1; f[l][r][0] = min (f[l + 1][r][0] + (n - len + 1) * (a[l + 1] - a[l]), f[l + 1][r][1] + (n - len + 1) * (a[r] - a[l])); f[l][r][1] = min (f[l][r - 1][1] + (n - len + 1) * (a[r] - a[r - 1]), f[l][r - 1][0] + (n - len + 1) * (a[r] - a[l])); } } print (min (f[1][n][0], f[1][n][1])); return0; }