1#include <bits/stdc++.h>23usingnamespace std;4// Oh I just realized it is not a greedy problem5// should have looked at the constraint6//it is a backtracking/dp question7//大意了没有闪8struct course {9int s, f, b, e, m, v, total;10};11int n, m;12vector<course> a;13bool bad[21][21];14bool chose[21];15longlong best =-1;16// index is next course to consider17// count is how many chosen so far18// sum is total value so far19voiddfs(int indx, int cnt, longlong sum){20if (cnt + (n - indx) < m) return; // stop if we cannot reach m even if we pick all courses21if(indx == n){22if(cnt >= m){23 best =max(best, sum);24return;25 }26 }27//if mandatory, we must include it 28if(a[indx].m){29bool good =true;30//check if conflict with previously chosen courses31for(int i =0; i < indx; i++){32if(chose[i] && bad[indx][i]){33 good =false;34break;35 }36 }37if(good){38 chose[indx] =true;39dfs(indx +1, cnt +1, sum + a[indx].total);40 chose[indx] =false;41 } // if we cannot chose mandatory, we cannot proceed with the current arrangement since mandatory cannot be satisfied 42 } else {43//skip optional course44dfs(indx +1, cnt, sum);45// if no conflict, try including it46bool good =true;47//check if conflict with previously chosen courses48for(int i =0; i < indx; i++){49if(chose[i] && bad[indx][i]){50 good =false;51break;52 }53 }54if(good){55 chose[indx] =true;56dfs(indx +1, cnt +1, sum + a[indx].total);57 chose[indx] =false;58 }59 }60}61intmain(){62 ios::sync_with_stdio(0);63 cin.tie(0);64 cin >> n >> m;65 a.resize(n);66for(int i =0; i < n; i++){67 cin >> a[i].s >> a[i].f >> a[i].b >> a[i].e >> a[i].m >> a[i].v;68 a[i].total = (a[i].f - a[i].s +1) * (a[i].e - a[i].b +1) * a[i].v;69 }70//preprocess conflicting 71for(int i =0; i < n; i++){72for(int j = i +1; j < n; j++){73bool bad_day =!(a[i].f < a[j].s || a[j].f < a[i].s); // i finishes before j starts or j finishes before i starts74bool bad_time =!(a[i].e < a[j].b || a[j].e < a[i].b); // the same for time75if(bad_day && bad_time) bad[i][j] = bad[j][i] =true; // conflict if on same day and at same time76 }77 }78//check if mandatory days conlfict each other or not , if yes then it is impossible 79int count =0;80for(int i =0; i < n; i++){81if(a[i].m){ // mandatory 82 count++;83for(int j = i +1; j < n; j++){84if(a[j].m && (bad[i][j] || bad[j][i])){85 cout <<-1<<'\n';86return0;87 }88 }89 }90 }91dfs(0, 0, 0LL);92 cout << best <<'\n';93return0;94}
☕
Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.
Python records executed lines and locals automatically. For selected values in any language, add // @trace i, total on its own valid line; Python uses # @trace i, total.
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.
Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.