ccf csp 201903-5 317号任务

#include<bits/stdc++.h>
using namespace std;
#define INF 0x7fffffff
const int maxn = 10000;
int n, m, k;
int matrix[maxn][maxn];
bool vis[maxn];
int dist[maxn];
bool type[maxn];

int dijkstra(int start){
	priority_queue<int> pq;
	memset(vis, 0, sizeof(vis));
	for(int i = 0; i < n; i++){
		dist[i] = matrix[start][i];
	}
	
	vis[start] = true;
	while(true){
		int minx = INF;
		int v;
		for(int i = 0; i < n; i++){
			if(dist[i] < minx && vis[i] == 0){
				minx = dist[i];
				v = i;
			}
		}
		if(minx >= INF) break;
		vis[v] = true;
		for(int i = 0; i < n; i++){
			if(!vis[i] && dist[i] > dist[v] + matrix[v][i]
				&& dist[v] < INF && matrix[v][i] < INF){
					dist[i] = dist[v] + matrix[v][i];
			}
		}
	}
	
	for(int i = 0; i < n; i++){
		if(type[i] == 1 && dist[i] < INF){
			pq.push(dist[i]);
		}
		if(pq.size() > k){
			pq.pop();
		}
	}
	
	long long res = 0;
	while(!pq.empty()){
		res += pq.top();
		pq.pop();
	}
	return res;
}

int main(){
	cin >> n >> m >> k;	
	
	for(int i = 0; i < maxn; i++){
		for(int j = 0; j < maxn; j++){
			if(i == j){
				matrix[i][j] = 0;
			}else{
				matrix[i][j] = INF;
				matrix[j][i] = INF;
			}
		}
	}

	for(int i = 0; i < n; i++){
		cin >> type[i];
	}
	
	for(int i = 0; i < m; i++){
		int u, v, w;
		cin >> u >> v >> w;
		if(u == v){
			continue;
		}else{
			matrix[u - 1][v - 1] = min(w, matrix[u - 1][v - 1]);
			matrix[v - 1][u - 1] = matrix[u - 1][v - 1];
		}
	}
	
	for(int i = 0; i < n; i++){
		cout << dijkstra(i) << endl;
	}
	
	return 0;
}

不保证完全通过,仅测试了样例。

上一篇:桐影317第五章小组讨论


下一篇:PAT A 1057 Stack (30分)