fork download
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <cassert>
  4. #include <cstring>
  5. #include <iostream>
  6. #include <cmath>
  7. #include <deque>
  8. #include <queue>
  9. #include <stack>
  10. #include <vector>
  11. #include <algorithm>
  12. #include <set>
  13. #include <map>
  14. #include <complex>
  15.  
  16. #define mp(a, b) make_pair((a), (b))
  17. #define pb(a) push_back((a))
  18. #define pf(a) push_front((a))
  19. #define rb() pop_back()
  20. #define rf() pop_front()
  21. #define sz(a) ((int)a.size())
  22.  
  23. using namespace std;
  24.  
  25. typedef long long lld;
  26. typedef pair<int, int> pii;
  27. typedef pair<lld, lld> pll;
  28. typedef pair<lld, int> pli;
  29. typedef pair<int, lld> pil;
  30. typedef vector<vector<int>> Matrix;
  31. typedef vector<vector<int>> Adj;
  32. typedef vector<int> Row;
  33. typedef complex<double> Complex;
  34. typedef vector<Complex> Vcomplex;
  35.  
  36. const int MOD = 1e9 + 7;
  37. const int INF = 1e9;
  38. const lld LINF = 1e18;
  39. const double FINF = 1e15;
  40. const double EPS = 1e-9;
  41. const double PI = 2.0 * acos(0.0);
  42.  
  43. int n, m;
  44. int d[1005][1005];
  45. int main() {
  46. cin >> n >> m;
  47. vector<int> a(n), b(m);
  48. for (int i = 0; i < n; ++i) cin >> a[i];
  49. for (int i = 0; i < m; ++i) cin >> b[i];
  50. if (n < m) swap(n, m), swap(a, b);
  51. sort(a.begin(), a.end());
  52. sort(b.begin(), b.end());
  53. for (int i = 0; i <= n; ++i) for (int j = 0; j <= m; ++j) d[i][j] = INF;
  54. d[0][0] = 0;
  55. for (int i = 0; i <= n; ++i) {
  56. for (int j = 0; j <= m; ++j) {
  57. if (i < n && j < m) d[i+1][j+1] = min(d[i+1][j+1], d[i][j] + abs(a[i] - b[j]));
  58. if (i < n) d[i+1][j] = min(d[i+1][j], d[i][j]);
  59. }
  60. }
  61. printf("%d\n", d[n][m]);
  62. }
  63.  
Success #stdin #stdout 0s 7420KB
stdin
2 1
10 20
15
stdout
5