POJ - 1062 limited the shortest

Topic Link
meaning of the questions
n each have a personal item, each item can be bought directly, you can also add a small amount of money to buy other items through mortgage, everyone has a rating, the maximum level after several poor people to buy exchange not exceed m. Seeking to get the first item of the minimum cost is how much?
Thinking
If no hierarchy is a constrained shortest path problem template, a transducer according to Item b Item of w added gold, may establish a directed edge a-> b, cost w. Then you can directly use the shortest, but because of constraints, can not be called directly. Consider the issue requirement to want to change a number of items, it is possible to exchange a population, the level difference can not exceed m, and the level range to include a level, because the smaller range of topics, direct enumeration interval, dijkstra take multiple calls to a minimum.
There is a little trick question does not specify a starting point, we can assume that 0 is the starting point for the establishment of an edge from 0 to each vertex, edge weights is the direct purchase price of the item.

#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
#define INF 0x3f3f3f3f
#define pr pair<int, int>
const int maxn = 1e5 + 7;
typedef long long ll;
int head[maxn], to[maxn<<1], nex[maxn<<1], edge[maxn<<1], cnt;
int n, m;
void init() {
    memset(head, -1, sizeof(head));
    cnt = 0;
}
void add(int x, int y, int z) {
    to[cnt] = y;
    edge[cnt] = z;
    nex[cnt] = head[x];
    head[x] = cnt++;
}
int d[maxn], p[maxn];
bool final[maxn];
void dijkstra(int l, int r)
{
	memset(final, 0, sizeof(final));
	memset(d, INF, sizeof(d));
	priority_queue<pr, vector<pr>, greater<pr> > q;
	q.push(make_pair(0, 0));//first是length,second是顶点
	d[0] = 0;
	while (!q.empty())
	{
		int u = q.top().second;
		q.pop();
		final[u] = true;
		for (int i = head[u]; ~i; i = nex[i])
		{
			int v = to[i];
			int len = edge[i];
			if(!final[v] && d[v] > d[u] + len && p[v] >= l && p[v] <= r)
			{
				d[v] = d[u] + len;
				q.push(make_pair(d[v], v));
			}
		}
	}
}
int main()
{
    init();
    scanf("%d %d", &m, &n);
    for (int i = 1; i <= n; i++) {
        int x;
        scanf("%d%d%d", &d[i], &p[i], &x);
        for (int j = 1; j <= x; j++) {
            int a, b;
            scanf("%d%d", &a, &b);
            add(a, i, b);
        }
    }
    for (int i = 1; i <= n; i++)
        add(0, i, d[i]);
    p[0] = p[1];
    int ans = INF;
    for (int i = max(0, p[1] - m); i - p[1] <= m; i++) {
        dijkstra(i, min(i + m, p[1] + m));
        ans = min(d[1], ans);
    }
    printf("%d\n", ans);
}

Published 26 original articles · won praise 2 · Views 404

Guess you like

Origin blog.csdn.net/D_Bamboo_/article/details/103620821