这题是与别的题解不同的思路。
对这题进行分析,发现 ,很小,果断选择模拟退火。
直接暴力求就可以了,然后你大概会写出这样的代码:
#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,原因在这一行:
else if (exp(-delta / T) * RAND_MAX > rand()) {
h[dx] = !h[dx];
}注意到这里变化很大,可以将其改为一下形式:
else if (100 * exp(-delta / T) * RAND_MAX > rand()) {
h[dx] = !h[dx];
}然后?AC 了。
#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;
}