UVALive - 4987 Evacuation Plan

题目

实在不敢相信瞎写居然过了。

思路:

都先排序。

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;
}

 

未来可期。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值