Advertisement
jonathanasdf

Batch Scheduling

May 8th, 2013
1,892
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. int N, S, t[10001], f[10001];
  7. int w(int i, int x) { return S*(f[N]-f[i]) + t[x]*(f[x]-f[i]); }
  8.  
  9. int main() {
  10.     cin >> N >> S;
  11.    
  12.     t[0] = 0; f[0] = 0;
  13.     for (int i=1; i <= N; i++) {
  14.         cin >> t[i] >> f[i];
  15.         t[i] += t[i-1];
  16.         f[i] += f[i-1];
  17.     }
  18.  
  19.     int dp[N+1]; dp[0] = 0;
  20.    
  21.     vector<pair<int, int> > v; // start pos, best-k
  22.     v.push_back(make_pair(0, 0));
  23.    
  24.     for (int x=1; x <= N; x++) {
  25.         // Find the value of dp[x]
  26.         int k = (--lower_bound(v.begin(), v.end(), make_pair(x+1, 0)))->second;
  27.         dp[x] = dp[k] + w(k, x);
  28.  
  29.         // Update the segments
  30.         for (int i = v.size()-1; i >= 0; i--) {
  31.             int y = v[i].first, oldk = v[i].second;
  32.             // Case 1
  33.             if (y > x && dp[x] + w(x, y) < dp[oldk] + w(oldk, y))
  34.                 v.pop_back();
  35.             // Case 2
  36.             else {
  37.                 int lo = y+1, hi = N+1;
  38.                 while(lo < hi) {
  39.                     int mid = (lo+hi)/2;
  40.                     if (dp[x] + w(x, mid) <= dp[oldk] + w(oldk, mid))
  41.                         hi = mid;
  42.                     else
  43.                         lo = mid+1;
  44.                 }
  45.                 if (hi != N+1) v.push_back(make_pair(hi, x));
  46.                 break;
  47.             }
  48.         }
  49.         if (v.size() == 0)
  50.             v.push_back(make_pair(0, x));
  51.     }
  52.     cout << dp[N] << endl;
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement