P2935
[USACO09JAN]Best Spot S
题目
约翰拥有P(1<=P<=500)个牧场.贝茜特别喜欢其中的F个.所有的牧场 由C(1 < C<=8000)条双向路连接,第i路连接着ai,bi,需要Ti(1<=Ti< 892)单 位时间来通过.
作为一只总想优化自己生活方式的奶牛,贝茜喜欢自己某一天醒来,到达所有那F个她喜欢的 牧场的平均需时最小.那她前一天应该睡在哪个牧场呢?请帮助贝茜找到这个最佳牧场.
此可见,牧场10到所有贝茜喜欢的牧场的平均距离最小,为最佳牧场.
输入
13 6 15
11
13
10
12
8
1
2 4 3
7 11 3
10 11 1
4 13 3
9 10 3
2 3 2
3 5 4
5 9 2
6 7 6
5 6 1
1 2 4
4 5 3
11 12 3
6 10 1
7 8 7
输出
10
点拨
根据题意,我们只需要求出这几个最喜爱的农场相对于每个点的距离,相加求最小值即可
对每个点要求最短路,时间复杂度为O(n^2*logn)
代码
#include <iostream>
#include <utility>
#include <queue>
using namespace std;
typedef long long ll;
#define fi(i, a, b) for (int i = a; i <= b; ++i)
#define fr(i, a, b) for (int i = a; i >= b; --i)
#define x first
#define y second
#define sz(x) ((int)(x).size())
#define pb push_back
using pii = pair<int, int>;
//#define DEBUG
int cnt = 1;
int head[505];
int dis[505][505];
int s[505];
int ans[505];
struct edge
{
int e, w, next;
} edge[16005];
void add(int a, int b, int c)
{
edge[cnt].e = b;
edge[cnt].w = c;
edge[cnt].next = head[a];
head[a] = cnt++;
}
struct node
{
int e, w;
bool operator<(const node p) const
{
return w > p.w;
}
};
int p, f, c;
void djstra(int s)
{
priority_queue<node> pri;
bool vis[505];
fi(i, 0, p) vis[i] = false;
pri.push({s, 0});
while (!pri.empty())
{
node temp = pri.top();
pri.pop();
int x = temp.e, y = temp.w;
vis[x] = true;
// cout << x << endl;
for (int j = head[x]; j != 0; j = edge[j].next)
{
int e = edge[j].e;
int w = edge[j].w;
// cout << e << " " << w << endl;
// cout << dis[s][e] << endl;
if (dis[s][e] >= dis[s][x] + w)
{
dis[s][e] = dis[e][s] = dis[s][x] + w;
// cout << e << " " << dis[s][e] << " ";
if(!vis[e])
pri.push({e, dis[s][e]});
}
}
}
fi(i, 1, p) ans[i] += dis[s][i];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
#ifdef DEBUG
// freopen(D:\in.txt,r,stdin);
#endif
cin >> p >> f >> c;
fi(i, 1, f) cin >> s[i];
fi(i, 1, p) fi(j, 1, p) dis[i][j] = 0x3f3f3f3f;
fi(i, 1, p) dis[i][i] = 0;
while (c--)
{
int a, b, c1;
cin >> a >> b >> c1;
add(a, b, c1);
add(b, a, c1);
dis[a][b] = dis[b][a] = c1;
}
// djstra(1);
fi(i, 1, f)
{
djstra(s[i]);
}
double res[505];
fi(i,1,p) res[i] = (double)ans[i]/f;
// fi(i, 1, p) cout << res[i] << " ";
// cout << endl;
double minn = 0x3f3f3f;
int minn1;
fi(i,1,p){
if(res[i] < minn){
minn = res[i];
minn1 = i;
}
}
cout << minn1 << endl;
return 0;
}