USACO butter
多次使用dijkstra就行, 代码如下:
/* ID: m1500293 LANG: C++ PROG: butter */ #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <vector> using namespace std; int N, P, C; //牛的数量 牧场的数量 边的数量 int cows[550]; struct edge { int to, cost; edge() {} edge(int to, int cost):to(to), cost(cost) {} }; vector<edge> G[810]; struct Dij { int u, cost; Dij() {} Dij(int u, int cost):u(u), cost(cost) {} bool operator<(const Dij &r) const { return cost > r.cost; } }; int dist[810], vis[810]; void dijkstra(int s) { memset(vis, 0, sizeof(vis)); memset(dist, 0x3f, sizeof(dist)); priority_queue<Dij> que; dist[s] = 0; que.push(Dij(s, 0)); while(!que.empty()) { Dij u = que.top(); que.pop(); if(vis[u.u]) continue; vis[u.u] = 1; for(int i=0; i<G[u.u].size(); i++) { edge e = G[u.u][i]; if(dist[e.to] > dist[u.u]+e.cost) { dist[e.to] = dist[u.u]+e.cost; que.push(Dij(e.to, dist[e.to])); } } } } int main() { freopen("butter.in", "r", stdin); freopen("butter.out", "w", stdout); scanf("%d%d%d", &N, &P, &C); for(int i=0; i<N; i++) scanf("%d", &cows[i]); for(int i=0; i<C; i++) { int u, v, cost; scanf("%d%d%d", &u, &v, &cost); G[u].push_back(edge(v, cost)); G[v].push_back(edge(u, cost)); } int sum=0x3fffffff; for(int i=1; i<=P; i++) { dijkstra(i); int tp = 0; for(int j=0; j<N; j++) { tp += dist[cows[j]]; // if(dist[cows[j]] == 0x3f3f3f3f) // { // tp = -1; // break; // } } // if(tp < 0) continue; if(tp < sum) sum = tp; } printf("%d\n", sum); return 0; }