Lang:G++
Edit12345678910111213141516171819202122232425262728293031#include<bits/stdc++.h>#define INF 0x3f3f3f3fusing namespace std;const int N = 100005;int n,m;int wi[N],hi[N],t[N];//given ith image and current w & h, return the h and w after attaching ith imagevoid attach(int i,int &w,int &h){if (w+wi[i] > m)h = max(h,(int)ceil(1.0*(m-w)*hi[i]/wi[i]));elseh = max(h, hi[i]);w = min(m, w+wi[i]);}//given ith image and current w & h, calculate total h after insert images from i to n//t[i] stores the gain in h after insert images from i to n to a new line.int calc(int i,int w,int h){while(i < n && w < m)attach(i++,w,h);return h+t[i];}void solve(){int ans = INF,w,h,preSum;w = h = preSum = 0;for(int i = 0; i < n; ++i){int tmp = calc(i+1,w,h);ans = min(ans, preSum+tmp);