Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Judge: https://zerojudge.tw/ShowProblem?problemid=c471
- #include <bits/stdc++.h>
- using namespace std;
- // This problem is a little harder than previous problems.
- // The idea is about greedy.
- // Let us consider situation when there're only two stuff: stuff A and B
- // If A stack on B, it costs f(A) * w(B), otherwise it costs f(B) * w(A).
- // Formally, if (f(A) * w(B) < f(B) * w(A)), we should let A stack on B to minimize the cost, and vice versa.
- //
- // Now we can extend to N stuff and sort them, and than calculate the answer!
- struct stuff{
- int w,f; //w => weight, f => times to take
- };
- stuff stuffs[100000];
- // compare function, for sorting usage
- bool cmp(stuff a, stuff b){
- return a.w*b.f < b.w*a.f;
- }
- int main(){
- // inputs
- int n;
- cin >> n;
- for(int i = 0; i < n; ++i){
- cin >> stuffs[i].w;
- }
- for(int i = 0; i < n; ++i){
- cin >> stuffs[i].f;
- }
- // sort method, see more details https://officeguide.cc/cpp-sort-function-tutorial-examples/
- sort(stuffs, stuffs + n, cmp);
- // declare the answer and the sum of weight
- // remember to use long long int to prevent from integer overflow
- long long int ans = 0, sum = 0;
- for(int i = 0; i < n; ++i){
- // calculation
- ans += sum * stuffs[i].f;
- sum += stuffs[i].w;
- }
- cout << ans << '\n';
- return 0;
- }
Add Comment
Please, Sign In to add comment