最多15个必须经过的城市 2进制表示
dp[i][j] 表示i这个状态下现在位置是第j个城市剩下的最大钱数
我日啊 id有一个错了 害我哇了12次 一发现一改马上AC 伤不起
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 110;
int INF = 999999999;
struct Li
{
int u, c, d;
}b[maxn];
int dp[1<<16][16];
int a[maxn][maxn];
int id[maxn];
int n, m, h, Money;
void floyd()
{
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(a[i][k] + a[k][j] < a[i][j])
a[i][j] = a[i][k] + a[k][j];
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d %d %d", &n, &m, &Money);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
if(i == j)
a[i][j] = 0;
else
a[i][j] = INF;
}
}
memset(id, 0, sizeof(id));
while(m--)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
if(a[u][v] > w)
{
a[u][v] = w;
a[v][u] = w;
}
}
scanf("%d", &h);
for(int i = 0; i < h; i++)
{
scanf("%d %d %d", &b[i].u, &b[i].c, &b[i].d);
id[i] = b[i].u;
}
memset(dp, -1, sizeof(dp));
floyd();
for(int i = 1; i < (1<<h); i++)
{
for(int j = 0; j < h; j++)
{
//dp[i][j] = INF;
if(i&(1<<j))
{
if(i == (1<<j))
{
if(Money - a[1][id[j]] - b[j].d >= 0)
dp[i][j] = Money - a[1][id[j]] - b[j].d + b[j].c;
continue;
}
for(int k = 0; k < h; k++)
{
if((i&(1<<k)) && (j != k))
{
if(dp[i^(1<<j)][k] == -1)
continue;
if(dp[i^(1<<j)][k] - a[id[k]][id[j]] - b[j].d >= 0)
{
dp[i][j] = max(dp[i][j], dp[i^(1<<j)][k] - a[id[k]][id[j]] - b[j].d + b[j].c);
//printf("%d %d %d\n", i, i^(1<<j), dp[i][j]);
}
}
}
}
}
}
//for(int i = 0; i < h; i++)
// printf("%d\n", dp[(1<<h)-1][i]);
int ans = -1;
for(int i = 0; i < h; i++)
ans = max(ans, dp[(1<<h)-1][i] - a[id[i]][1]);
if(ans >= 0)
puts("YES");
else
puts("NO");
}
return 0;
}