Grammy and Jewelry Gym - 103055J(链式前向星 + Dijkstra算法 + 完全背包)-- 笔记

该程序解决了一个关于在一个有向图中,从顶点1开始在限定时间内收集最多价值珠宝的问题。Dijkstra算法用于计算每个节点到起点的最短路径,接着采用完全背包策略计算在不同时间限制下的最大珠宝总价值。程序通过读取图的结构和珠宝价值,然后执行路径搜索和背包问题求解,最后输出每个时间步长的最大价值。
摘要由CSDN通过智能技术生成

题目

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值