poj 1251  && hdu 1301

Sample Input

9 //n 结点数
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
3
A 2 B 10 C 40
B 1 C 20
0
Sample Output

216
30

 

prim算法

 1 # include <iostream>
 2 # include <cstdio>
 3 # include <cstring>
 4 # include <algorithm>
 5 # include <cmath>
 6 # define LL long long
 7 using namespace std ;
 8 
 9 const int INF=0x3f3f3f3f;
10 const int MAXN=110;
11 bool vis[MAXN];
12 int lowc[MAXN];
13 int n ;
14 int cost[MAXN][MAXN] ;
15 
16 int Prim()//点是0~n-1
17 {
18     int ans=0;
19     memset(vis,false,sizeof(vis));
20     vis[0]=true;
21     for(int i=1;i<n;i++)lowc[i]=cost[0][i];
22     for(int i=1;i<n;i++)
23     {
24         int minc=INF;
25         int p=-1;
26         for(int j=0;j<n;j++)
27             if(!vis[j]&&minc>lowc[j])
28             {
29                 minc=lowc[j];
30                 p=j;
31             }
32             if(minc==INF)return -1;//原图不连通
33             ans+=minc;
34             vis[p]=true;
35             for(int j=0;j<n;j++)
36                 if(!vis[j]&&lowc[j]>cost[p][j])
37                     lowc[j]=cost[p][j];
38     }
39     return ans;
40 }
41 
42 int main()
43 {
44 
45    // freopen("in.txt","r",stdin) ;
46     while(cin>>n)
47     {
48         if (n == 0)
49             break ;
50         char u , v;
51         int w , num ;
52         int i , j ;
53         for (i = 0 ; i < n ; i++)
54             for (j = 0 ; j < n ; j++)
55                cost[i][j] = INF ;
56         
57         for (i = 1 ; i < n ; i++)
58         {
59             cin>>u>>num ;
60             while (num--)
61             {
62                 cin>>v>>w ;
63                 cost[u -'A'][v - 'A'] = w ;
64                 cost[v - 'A'][u -'A'] = w ;
65             }
66         }
67         cout<<Prim()<<endl ;
68 
69     }
70     return 0 ;
71 }
View Code

相关文章:

  • 2021-06-10
  • 2021-10-02
  • 2022-12-23
  • 2021-11-06
  • 2021-09-26
  • 2022-01-29
  • 2021-10-11
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2021-10-03
  • 2022-12-23
  • 2021-09-14
相关资源
相似解决方案