HDU 2851 dp 与 dijkstra

#include <bits/stdc++.h>
using namespace std;
const int MAX_V = 2005;
const int INF = 0x3f3f3f3f;
struct rode
{
	int start, end, danger;
};
int n, m;
int *dp;
rode *p;
void solve()
{
	dp[0] = p[0].danger;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < i; j++)
		{
			if (p[j].end >= p[i].start)
				dp[i] = min(dp[i], dp[j] + p[i].danger);
		}
	}
}
int main(int argc, char const *argv[])
{
	int kase;
	cin >> kase;
	while (kase--)
	{
		cin >> n >> m;
		p = new rode[n];
		dp = new int[n];
		for (int i = 0; i < n; i++)
			cin >> p[i].start >> p[i].end >> p[i].danger;
		fill(dp, dp + n, INF);
		solve();
		while (m--)
		{
			int inp;
			cin >> inp;
			cout << (dp[inp - 1] == INF ? -1 : dp[inp - 1]) << endl;
		}
		delete[] p, dp;
	}
	return 0;
}
dp 算法:

dp[i] = min(dp[i], dp[j] + p[i].danger);

#include <bits/stdc++.h>
using namespace std;
struct edge
{
	int to, cost;
	bool operator>(edge &p)
	{
		return cost > p.cost;
	}
	edge(int a, int b): to(a), cost(b) {}
};
const int MAX_V = 2001;
typedef pair<int, int>P;
int v;
std::vector<edge> G[MAX_V];
int d[MAX_V];
const int INF = 0x3f3f3f3f;
void dijkstra(int s)
{
	priority_queue<P, vector<P> >que;
	fill(d, d + v, INF);
	d[s] = 0;
	que.push(P(0, s));
	while (!que.empty())
	{
		P p = que.top();
		que.pop();
		int v = p.second;
		if (d[v] < p.first)
			continue;
		for (int i = 0; i < G[v].size(); i++)
		{
			edge e = G[v][i];
			if (d[e.to] > d[v] + e.cost)
			{
				d[e.to] = d[v] + e.cost;
				que.push(P(d[e.to], e.to));
			}
		}
	}
}
struct rode
{
	int start, end, danger;
};
int main(int argc, char const *argv[])
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	int kase;
	cin >> kase;
	while (kase--)
	{
		int n, m;
		cin >> n >> m;
		v = n;
		memset(d, 0, sizeof(d));
		for (int i = 0; i < n; i++)
			G[i].clear();
		rode pro[MAX_V];
		for (int i = 0; i < n; ++i)
			cin >> pro[i].start >> pro[i].end >> pro[i].danger;
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < i; j++)
			{
				if (pro[j].end >= pro[i].start)
				{
					G[j].push_back(edge(i, pro[i].danger));
					//cout << i << " " << j << " " << pro[i].danger << endl;
				}
			}
		}
		dijkstra(0);
		for (int i = 0; i < m; i++)
		{
			int t;
			cin >> t;
			cout << ((d[t - 1] == INF) ? -1 : d[t - 1] + pro[0].danger) << endl;

		}
	}
	return 0;
}
 dijkstra算法:不知为何超时

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值