做題記錄#2
阿新 • • 發佈:2021-10-19
Sonya and Problem Wihtout a Legend
來源:CF713C, 2300
直接弄這個嚴格遞增序列不好搞,不妨考慮嚴格遞增需要滿足的條件.
發現,條件為 $\mathrm{i-j\leqslant a[i]-a[j]}$ 對任意 $\mathrm{i,j}$ 都成立.
然後化簡一下就是 $\mathrm{a[j]-j \leqslant a[i]-i}$.
令 $\mathrm{c[i]}$ 表示化簡後的結果,那隻需令 $\mathrm{c[i]}$ 不減就行.
由不減的性質,序列中數字種類肯定不會變.
所以可以設 $\mathrm{f[i][j]}$ 表示前 $\mathrm{i}$ 個數,最後為 $\mathrm{j}$ 的修改次數.
這個東西用 $\mathrm{DP}$ 求一下就好了.
#include <cstdio> #include <vector> #include <cstring> #include <algorithm> #define N 3009 #define ll long long #define pb push_back #define setIO(s) freopen(s".in","r",stdin) using namespace std; int n , cnt ; int a[N], c[N], A[N]; ll f[N][N]; int main() { // setIO("input"); scanf("%d",&n); for(int i=1;i<=n;++i) { scanf("%d",&a[i]); c[i] = a[i] - i; } cnt = n ; c[++ cnt] = -N; for(int i=1;i<=cnt;++i) A[i]=c[i]; sort(A+1,A+1+cnt); for(int i=1;i<=cnt;++i) c[i]=lower_bound(A+1,A+1+cnt,c[i])-A; memset(f, 0x3f, sizeof(f)); f[0][1] = 0; ll fin = 1000000000000000ll; for(int i=1;i<=n;++i) { ll mi = f[i - 1][1]; for(int j=1;j<=cnt;++j) { mi = min(mi, f[i - 1][j]); f[i][j] = abs(A[c[i]] - A[j]) + mi; if(i == n) fin = min(fin, f[i][j]); } } printf("%lld\n", fin); return 0; }
Make k Equal
來源:CF1328F, 2200
思考最後的形式:
設答案為 $\mathrm{fin}$, 需要大於 $\mathrm{fin}$ 的都變為 $\mathrm{fin+1}$, 然後從中挑選不夠的補齊.
對於小於 $\mathrm{fin}$ 的情況同理.
顯然,答案只可能為序列中原數,或者相差值為 $1$ 的數字.
直接列舉答案然後利用字首和算一算就好了.
#include <cstdio> #include <vector> #include <cstring> #include <algorithm> #include <map> #define N 600009 #define ll long long #define pb push_back #define setIO(s) freopen(s".in","r",stdin) using namespace std; int n,K,cnt; ll suf[N],pre[N]; int a[N],A[N],B[N]; map<int,int>co; int get_pre(int pos) { // 求 <= pos 的個數. int p = lower_bound(B + 1, B + 1 + 1 + n, pos + 1) - B; return p - 1; } int get_aft(int pos) { // 求 >= pos 的個數. return n - get_pre(pos - 1); } int main() { // setIO("input"); scanf("%d%d",&n,&K); for(int i=1;i<=n;++i) { scanf("%d",&a[i]); B[i] = a[i]; co[a[i]] ++ ; if(co[a[i]] >= K) { printf("0\n"); return 0; } A[++cnt] = a[i]; A[++cnt] = a[i] - 1; A[++cnt] = a[i] + 1; } B[n + 1] = 1200000000; sort(B+1, B+1+n); for(int i = n; i >= 1; -- i) suf[i] = suf[i + 1] + 1ll * B[i]; for(int i = 1; i <= n ; ++ i) pre[i] = pre[i - 1] + 1ll * B[i]; sort(A+1, A+1+cnt); ll ans = 10000000000000000ll; for(int i=1;i<=cnt;++i) { // 計算 A[i] 的答案. int num = co[A[i]]; int det = K - num; int prfix = get_pre(A[i] - 1); int sufix = get_aft(A[i] + 1); if(prfix >= det || sufix >= det) { if(prfix >= det) { ll dprfix = 1ll * prfix * (A[i] - 1) - pre[prfix]; ans = min(ans, dprfix + det); } if(sufix >= det) { ll dsufix = suf[n - sufix + 1] - 1ll * sufix * (A[i] + 1); ans = min(ans, dsufix + det); } } else { // 需要都到達目的地. ll dsufix = suf[n - sufix + 1] - 1ll * sufix * (A[i] + 1) ; ll dprfix = 1ll * prfix * (A[i] - 1) - pre[prfix]; ans = min(ans, dsufix + dprfix + det); } } printf("%lld\n", ans); return 0; }