CodeForces - 1525D Armchairs(dp)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1525D Armchairs(dp)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個長度為 nnn 的 010101 數列,現在可以執行的操作是:花費代價 abs(i?j)abs(i-j)abs(i?j),使得 aia_iai? 和 aja_jaj? 交換,問最少需要花費多少代價,可以使得原本為 111 的位置全部變為 000,題目保證一定有解
題目分析:因為保證了一定有解,一開始以為就是個裸的費用流,交了一發果不其然 T 掉了,所以考慮 dp
考慮一個貪心的性質,假設初始時 111 所在的位置排序后分別為 x1,x2,...,xkx_1,x_2,...,x_kx1?,x2?,...,xk?,同時操作后為 111 的位置分別為 y1,y2,...,yky_1,y_2,...,y_ky1?,y2?,...,yk?,顯然讓 xix_ixi? 移動到 yiy_iyi? 的位置一定是一種最優的方案
所以可以去進行 dp,即 dpi,jdp_{i,j}dpi,j? 代表到了第 iii 個位置,已經安排了前 jjj 個 111 到相應位置的最小代價,對于每個 000 所在的位置,我們可以考慮將第 jjj 個 111 放在這里,也可以什么都不操作,于是就轉變為了一個比較簡單的 dp 了
代碼:
// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=5e3+100; int a[N],dp[N][N]; vector<int>pos; int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int n;read(n);for(int i=1;i<=n;i++) {read(a[i]);if(a[i]) {pos.push_back(i);}}memset(dp,inf,sizeof(dp));int k=pos.size();dp[0][0]=0;for(int i=1;i<=n;i++) {for(int j=0;j<=k;j++) {dp[i][j]=min(dp[i][j],dp[i-1][j]);}if(a[i]==0) {for(int j=1;j<=k;j++) {dp[i][j]=min(dp[i][j],dp[i-1][j-1]+abs(pos[j-1]-i));}}}printf("%d\n",dp[n][k]);return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1525D Armchairs(dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1514D C
- 下一篇: CodeForces - 1509C T