牛客NOIP集训六J *世界 TJ

题目链接

思路

以后再也不用 \(Floyd\) 了,堆优化 \(Dijkstra\) 首选。
预处理最短路,\(k\) 个点枚举即可。

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 2e3 + 10;
priority_queue <pair <int ,int > ,vector < pair <int ,int > > ,greater < pair <int ,int > > > s;
vector <pair <int ,int > > c[MAXN];
int n ,m ,ans = 0 ,k;
int p[MAXN];
int dis[MAXN][MAXN] ,vis[MAXN];
void dijkstra (int st) {
	memset (vis ,0 ,sizeof (vis));
	dis[st][st] = 0;
	s.push(make_pair (0 ,st));
	while (!s.empty()) {
		int u = s.top().second;
		s.pop();
		if (vis[u]) continue ;
		vis[u] = 1;
		for (int q = 0;q < c[u].size();++ q) {
			int v = c[u][q].first ,w = c[u][q].second;
			if (dis[st][v] > dis[st][u] + w && ! vis[v]) {
				dis[st][v] = dis[st][u] + w;
				s.push(make_pair (dis[st][v] ,v));
			}
		}
	}
}
int main () {
	memset (dis ,0x3f ,sizeof (dis));
	scanf ("%d%d%d",&n ,&m ,&k);
	int from ,to ,w;
	for (int q = 1;q <= m;++ q) {
		scanf ("%d%d%d",&from ,&to ,&w);
		c[from].push_back(make_pair (to ,w));
		c[to].push_back(make_pair (from ,w));
	}
	for (int q = 1;q <= k;++ q) {
		scanf ("%d",&p[q]);
	}
	for (int q = 1;q <= n;++ q) {
		dijkstra (q);
	}
	for (int q = 1;q < n;++ q) {
		int sum = dis[q][q + 1];
		for (int w = 1;w <= k;++ w) {
			sum = min (sum ,dis[p[w]][q + 1]);
		}
		ans += sum;
	}
	
	printf ("%d\n",ans);
	return 0;
}

珍爱分数,远离 \(Floyd\) 和 \(SPFA\)。

上一篇:UVA297 四分树 Quadtrees TJ


下一篇:Java-id生成