题目
There is a connected undirected graph with nn vertices and mm edges. Vertices are indexed from 11 to nn. There is infinite jewelry in vertex ii (2≤i≤n2≤i≤n), each valued aiai. Grammy starts at point 11. Going through each edge consumes 11 unit of time. She can pick up a piece of jewelry at vertex ii and put it down at vertex 11. Picking up and putting down a piece of jewelry can be done instantly. Additionally, she can carry at most 1 piece of jewelry at any time. When she put down a piece of jewelry valued xx at vertex 11, she obtains the value of it. Now, for each kk between 11 and TT (inclusive) she wonders what is the maximum value she can get in kk units of time.
思路
求出图中每个点到起点(1)的最短路径,然后用完全背包求最大价值(这里用前向星构图,Dijkstra求最短路)
#include <iostream>
#include <queue>
#include <cstdio>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
int cnt, head[3005], a[3005], dis[3005], dp[3005];
bool done[3005];
struct Node {
int to, w, next;
}edges[100005];
struct s_node {
int u, n_dis;
s_node(int a, int b) { u = a; n_dis = b; }
bool operator < (const s_node& a) const {
return n_dis > a.n_dis;
}
};
void add(int u, int to, int w) {
edges[++cnt].to = to;
edges[cnt].w = w;
edges[cnt].next = head[u];
head[u] = cnt;
}
void dijkstra() {
int start = 1;
dis[start] = 0;
priority_queue<s_node> Q;
Q.push(s_node(1, 0));
while (!Q.empty()) {
s_node t = Q.top();
int i;
Q.pop();
if (done[t.u]) continue;
done[t.u] = true;
for (i = head[t.u]; i != 0; i = edges[i].next) {
int i_to = edges[i].to, i_w = edges[i].w;
if (done[i_to]) continue;
if (dis[i_to] > i_w + t.n_dis) {
dis[i_to] = i_w + t.n_dis;
Q.push(s_node(i_to, dis[i_to]));
}
}
}
}
/* 打印所有边,检验构图是否正确
void printedges(int u) {
for (int i = head[u]; i != 0; i = edges[i].next) {
printf("%d---%d: %d\n", u, edges[i].to, edges[i].w);
}
}*/
int main() {
int n, m, t;
scanf("%d%d%d", &n, &m, &t);
int i, j;
for (i = 0; i <= n; i++) {
head[i] = 0;
dp[i] = 0;
dis[i] = INF;
done[i] = false;
}
cnt = 0;
a[1] = 0;
for (i = 2; i <= n; i++) scanf("%d", a + i);
int x, y;
while (m--) {
scanf("%d%d", &x, &y);
if (x == y) continue;
add(x, y, 1);
add(y, x, 1);
}
/*for (i = 1; i <= n; i++) {
printedges(i);
}*/
dijkstra();
for (i = 2; i <= n; i++) {
for (j = 2 * dis[i]; j <= t; j++) {
dp[j] = max(dp[j], dp[j - dis[i] * 2] + a[i]);
}
}
for (i = 1; i <= t; i++) {
printf("%d%c", dp[i], i == t ? '\n' : ' ');
}
return 0;
}