Hdu1789doing homework again (Greedy)
Question Link
I will give you the deadline for n jobs and the scores you don't need to be deducted after this deadline. I will ask you how to make the minimum deduction.
Solution: greedy: place jobs with more points before the deadline, place the jobs with the same points before the deadline, and then use an array to indicate whether there is an arrangement for day I. Every time I put the first job on the day of its deadline to complete, but if this day is occupied, then it can only move forward to find the idle day. If 0 is found all the time, it indicates that this job cannot be completed on time, and the score is added. If the deadline for a job to be completed is greater than N, the job can be completed in a timely manner.
Code:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 1e3 + 5;int vis[maxn];int n;struct homework { int deadt, score;}h[maxn];int cmp (const homework &a, const homework &b) { if (a.score != b.score) return a.score > b.score; return a.deadt < b.deadt;}int solve () { sort(h, h + n, cmp); memset (vis, -1, sizeof (vis)); int ans = 0, time; for (int i = 0; i < n; i++) { time = h[i].deadt - 1; if (time >= n) continue; while (time >= 0 && vis[time] != -1) { time--; } if (time >= 0) vis[time] = 1; else ans += h[i].score; } return ans;}int main () { int T; scanf ("%d", &T); while (T--) { scanf ("%d", &n); for (int i = 0; i < n; i++) scanf ("%d", &h[i].deadt); for (int i = 0; i < n; i++) scanf ("%d", &h[i].score); printf ("%d\n", solve()); } return 0;}
Hdu1789doing homework again (Greedy)