跳到正文

题解

题解:P1064 [NOIP 2006 提高组] 金明的预算方案

Python_enjoy约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年8月17日
收录
2026年8月17日
更新
2026年11月7日
篇幅
约 5 分钟
题目
P1064

版本

  1. v1当前

这题是与别的题解不同的思路。

对这题进行分析,发现 m≤60m\leq60,很小,果断选择模拟退火。

直接暴力求就可以了,然后你大概会写出这样的代码:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 60 + 5;
int n, v[N], p[N], q[N], m;
int h[N];
int now;
int best;
int energy() {
	for (int i = 1; i <=m; i++) {
		if(h[i]) {
			if(h[q[i]]==0) {
				return -1;
			}
		}
	}
	int tot = 0;
	int ans = 0;
	for(int i = 1; i <= m; i++) {
		if(h[i]) {
			ans += v[i] * p[i];
			tot +=v[i];
		}
		if(tot > n) {
			return -1;
		}
	}
	return ans;
}

const double sT = 1e3;
const double eT = 1e-7;
const double dn = 0.9;
void SA() {
	double T = sT;
	while (T > eT) {
		int dx = rand() % m + 1;
		h[dx] = !h[dx];
		int temp = energy();
		h[dx] = !h[dx];
		if(temp == -1) {
			continue;
		}
		int delta = now - temp;
		best = max(best, temp);
		if (delta < 0) {
			now = temp;
			h[dx] = !h[dx];
		}
		else if (exp(-delta / T) * RAND_MAX > rand()) {
			h[dx] = !h[dx];
		}
		T *= dn;
	}
}
signed main() {
	srand(time(0));
	h[0] = true;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> v[i] >> p[i] >> q[i];
	}
	while (((double)clock()/CLOCKS_PER_SEC) < 0.98) {
		SA();
	}
	cout << best;
	return 0;
} 

可以发现只有 80pts,原因在这一行:

C++
else if (exp(-delta / T) * RAND_MAX > rand()) {
	h[dx] = !h[dx];
}

注意到这里变化很大,可以将其改为一下形式:

C++
else if (100 * exp(-delta / T) * RAND_MAX > rand()) {
	h[dx] = !h[dx];
}

然后?AC 了。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 60 + 5;
int n, v[N], p[N], q[N], m;
int h[N];
int now;
int best;
int energy() {
	for (int i = 1; i <=m; i++) {
		if(h[i]) {
			if(h[q[i]]==0) {
				return -1;
			}
		}
	}
	int tot = 0;
	int ans = 0;
	for(int i = 1; i <= m; i++) {
		if(h[i]) {
			ans += v[i] * p[i];
			tot +=v[i];
		}
		if(tot > n) {
			return -1;
		}
	}
	return ans;
}

const double sT = 1e3;
const double eT = 1e-7;
const double dn = 0.9;
void SA() {
	double T = sT;
	while (T > eT) {
		int dx = rand() % m + 1;
		h[dx] = !h[dx];
		int temp = energy();
		h[dx] = !h[dx];
		if(temp == -1) {
			continue;
		}
		int delta = now - temp;
		best = max(best, temp);
		if (delta < 0) {
			now = temp;
			h[dx] = !h[dx];
		}
		else if (100 * exp(-delta / T) * RAND_MAX > rand()) {
			h[dx] = !h[dx];
		}
		T *= dn;
	}
}
signed main() {
	srand(time(0));
	h[0] = true;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> v[i] >> p[i] >> q[i];
	}
	while (((double)clock()/CLOCKS_PER_SEC) < 0.98) {
		SA();
	}
	cout << best;
	return 0;
} 
原文