洛谷 P1364 医院设置

时间:2023-01-01 14:32:49

题目传送门

解题思路:

先Floyd一遍,求出每个点到其他任意一个点的距离,再暴力更新以每个点为源点的最短路.这题数据范围好水

AC代码:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 int n,a[101],dist[101][101],sum[101],ans = 0x7f7f7f7f; 
 8 
 9 int main()
10 {
11     memset(dist,100000007,sizeof(dist));
12     scanf("%d",&n);
13     for(int i = 1;i <= n; i++) {
14         int x,y;
15         scanf("%d%d%d",&a[i],&x,&y);
16         dist[i][i] = 0;
17         if(x != 0) dist[x][i] = dist[i][x] = 1;
18         if(y != 0) dist[i][y] = dist[y][i] = 1;
19     }
20     for(int k = 1;k <= n; k++)
21         for(int i = 1;i <= n; i++)
22             if(i != k)
23                 for(int j = 1;j <= n; j++) 
24                     if(i != j && j != k)
25                         dist[i][j] = min(dist[i][k] + dist[k][j],dist[i][j]);
26     for(int i = 1;i <= n; i++) {
27         for(int j = 1;j <= n; j++) 
28             if(i != j) 
29                 sum[i] = sum[i] + a[j] * dist[i][j]; 
30         ans = min(ans,sum[i]);
31     }    
32     printf("%d",ans);        
33     return 0;
34 }