PTA 双十一

题目大意
双十一期间,某著名电商平台“东东”为应对销售高峰,准备在 n n n 个城市中再增加一个自营仓库,其要求是该仓库设在 n n n 个城市中的某个城市,且距离其他所有城市的最短距离之和最小。请编写程序帮助“东东”找出设立仓库的地点。假定 n n n 个城市编号为 0 至 n n n -1,它们之间至少有一个城市与其他所有城市可及。
输入格式
输入包含多组数据。每组数据第一行为两个正整数 n n n e e e,均不超过100。 n n n 表示城市数。接下来 e e e 行表示两个城市间的距离信息,每行为 3 个非负整数 a 、 b 、 c a、b、c abc,其中 a a a b b b 表示两个城市编号, c c c 表示城市间的距离。
提示:可使用 E O F EOF EOF 判断输入结束。
输出格式
输出为一个整数,表示建立仓库的城市编号,如多个城市满足要求,则输出编号最小者。
输入样例

6 5
0 1 1
0 2 1
0 3 1
0 4 1
0 5 1
4 5
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1

输出样例

0
1

F l o y e d Floyed Floyed 求多源最短路径,先求出每个点到所有点的路径,最后求一下和,第一个点往最后一个点暴力枚举找最小值即可,输出该点,时间复杂度 O ( n 3 ) O(n^3) O(n3)

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 107;
typedef long long ll;
int mp[107][107];
int main()
{
    
    
    int n,e;
    while(~scanf("%d %d",&n,&e))
    {
    
    
        memset(mp, 0x3f, sizeof mp);
        for(int i = 1; i <= e; i++)
        {
    
    
            int from, to, v;
            scanf("%d %d %d",&from,&to,&v);
            ++from, ++to;
            if(from == to) mp[from][to] = 0;
            else
            {
    
    
                mp[from][to] = v;
                mp[to][from] = v;
            }
        }
        
        for(int k = 1; k <= n; k++)
            for(int i = 1; i <= n; i++)
                for(int j = 1; j <= n; j++)
                    if(mp[i][j] > mp[i][k] + mp[k][j])
                        mp[i][j] = mp[i][k] + mp[k][j];
        
        ll dis[maxn] = {
    
    0};
        for(int i = 1; i <= n; i++)
        {
    
    
            for(int j = 1; j <= n; j++)
            {
    
    
                if(i != j) dis[i] = dis[i] + (ll)mp[i][j];
            }
        }
        ll ans = 0x3f3f3f3f;
        int pos = 1;
        for(int i = 1; i <= n; i++)
            if(dis[i] < ans) ans = dis[i], pos = i;
        --pos;
        printf("%d\n",pos);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Edviv/article/details/111715914
PTA