Graph HDU - 4725 The Shortest Path in Nya (layered construction diagram)

HDU - 4725 topic Link

Subject to the effect

This is a hierarchical diagram.

  • Point between layers can reach each other, but if there is no edge, it can not be connected directly to the point in the same layer.
  • There are some points between the connected side, you can communicate directly without going through the floor, of course, also be faster if the floor by then.

Difficulties and handling

m side edges to establish simple, the key point is how to handle the relationship between good layers.

We additionally introduced n points serve as floors, number n + 1 ~ n + n
we establish direct current floor edge point, attention must be the same floor where the sides Unidirectional

Below, we assume that the first layer 2 point, 3 point, the second layer, and there is no edge between each point can reach each other, the cost spent on each floor
of from 1 -> 2 is only one way, go from point 1 of the first layer, the second layer 3 point, and then went to the point of the first layer 2 second layer 3 by a dot, is cost 2cost

If we establish a point on the floor and the floor side two-way, point 1-- spending is 0> 2 a.
Therefore, we must establish a unified side between points on the floor and then the floor, from the floor to point, point to the floor or from

//Powered by CK 2020:04:08
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 10;
int head[N], to[N], value[N], nex[N], cnt;
int visit[N], dis[N], n, m, cost;
struct cmp {
	bool operator () (const PII & a, const PII & b) const {
		return a.second > b.second;
	}
};
void add(int x, int y, int w) {
	to[cnt] = y;
	value[cnt] = w;
	nex[cnt] = head[x];
	head[x] = cnt++;
}
int Dijkstra() {
	memset(dis, 0x3f, sizeof dis);
	memset(visit, 0, sizeof visit);
	priority_queue<PII, vector<PII>, cmp> q;
	q.push(make_pair(1, 0));
	dis[1] = 0;
	while(!q.empty()) {
		int temp = q.top().first;
		q.pop();
		if(visit[temp])	continue;
		visit[temp] = 1;
		for(int i = head[temp]; i; i = nex[i]) {
			if(dis[to[i]] > dis[temp] + value[i]) {
				dis[to[i]] = dis[temp] + value[i];
				q.push(make_pair(to[i], dis[to[i]]));
			}
		}
	}
	return dis[n] == INF ? -1 : dis[n];
}
int main() {
	// freopen("in.txt", "r", stdin);
	int t, x, y, w;
	scanf("%d", &t);
	for(int cas = 1; cas <= t; cas++) {
		printf("Case #%d: ", cas);
		scanf("%d %d %d", &n, &m, &cost);
		memset(head, 0, sizeof head);
		cnt = 1;
		for(int i = 1; i<= n; i++) {
			scanf("%d", &x);
			add(i, x + n, 0);//点到楼层
			// add(x + n, i, 0);//楼层到点————二选一
			if(x - 1 >= 1)	add(x - 1 + n, i, cost), add(i, x - 1 + n, cost);
			if(x + 1 <= n)	add(x + 1 + n, i, cost), add(i, x + 1 + n, cost);
		}
		for(int i = 0; i < m; i++) {
			scanf("%d %d %d", &x, &y, &w);
			add(x, y, w);
			add(y, x, w);
		}
		printf("%d\n", Dijkstra());
	}
	return 0;
}

Guess you like

Origin www.cnblogs.com/lifehappy/p/12661859.html
Recommended