很明显的最小生成树模板题 多点生成
[cpp] view plaincopy
- #include<bits/stdc++.h>
- using namespace std;
- int n,k,a;
- int dist[120],m[120][120];
- bool p[120];
- void prim()
- {
- for(int i=1;i<=n;i++)
- {
- if(!p[i])
- {
- int Min=100020;
- for(int j=1;j<=n;j++)
- {
- if(p[j]&&m[i][j]<Min)
- Min=m[i][j];
- }
- dist[i]=Min;
- }
- }
- for(int i=1;i<=n-k;i++)
- {
- int Min=INT_MAX,k=0;
- for(int j=1;j<=n;j++)
- {
- if(!p[j]&&dist[j]<Min)
- {
- Min=dist[j];
- k=j;
- }
- }
- if(k==0)
- return;
- p[k]=true;
- for(int j=1;j<=n;j++)
- {
- if(!p[j]&&dist[j]>m[k][j])
- dist[j]=m[k][j];
- }
- }
- }
- int main()
- {
- memset(p,false,sizeof(p));
- scanf("%d%d",&n,&k);
- for(int i=1;i<=k;i++)
- {
- scanf("%d",&a);
- dist[a]=0;
- p[a]=true;
- }
- for(int i=1;i<=n;i++)
- for(int j=1;j<=n;j++)
- scanf("%d",&m[i][j]);
- prim();
- int sum=0;
- for(int i=1;i<=n;i++)
- sum+=dist[i];
- printf("%d\n",sum);
- return 0;
- }
Ural 1982 Electrification Plan (prim最小生成树)
时间: 2024-08-10 23:28:01