实在不敢相信瞎写居然过了。
思路:
都先排序。
dp[i][j]表示i支部队守护了j个避难所。
dp[i][j] = min(dp[i - 1][j - 1] + dist[i][j], dp[i - 1][j] + dist[i][j]);
得到最优解之后,从后往前处理路径。
最远的部队一定是守护最远得避难所,之后的每一支部队一定是守护之前部队守护的或者前一个避难所。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vll;
const int MAXN = 1e6 + 10;
const ll INF = 0x3f3f3f3f;
const ll MOD = 1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1.0);
int n, m, k;
typedef struct Node{
int pos, id;
Node(int a, int b){
pos = a;
id = b;
}
bool operator < (const Node &rhs) const{
return pos < rhs.pos;
}
}Node;
vi ans;
vector<vll> dp;
vector<Node> A, B;
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
cout << setprecision(10) << fixed;
while(cin >> n){
A.clear();
for(int i = 0; i < n; i++){
int pos;
cin >> pos;
A.push_back(Node(pos, i));
}
sort(A.begin(), A.end());
cin >> m;
B.clear();
for(int i = 0; i < m; i++){
int pos;
cin >> pos;
B.push_back(Node(pos, i));
}
sort(B.begin(), B.end());
dp.clear();
dp.resize(n, vll(m, INF * INF));
dp[0][0] = abs(A.front().pos - B.front().pos);
for(int i = 1; i < n; i++)
for(int j = 0; j <= min(m - 1, i); j++){
if(j)
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + abs(A[i].pos - B[j].pos));
dp[i][j] = min(dp[i][j], dp[i - 1][j] + abs(A[i].pos - B[j].pos));
}
cout << dp[n - 1][m - 1] << endl;
ans.clear();
ans.resize(n);
int last = m - 1;
for(int i = n - 1; i >= 0; i--){
int cur = last;
for(int j = last + 1; j < m; j++)
if(dp[i][j] < dp[i][cur])
cur = j;
ans[A[i].id] = B[cur].id + 1;
last = max(0, cur - 1);
}
for(int i = 0; i < n; i++){
if(i)
cout << " ";
cout << ans[i];
}
cout << endl;
}
cerr << "execute time : " << (double)clock() / CLOCKS_PER_SEC << endl;
return 0;
}
未来可期。