Total Submission(s) : 75 Accepted Submission(s) : 50
9 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
216 30
(1)大意:
(2)思路:
就是对给定的图,求出最小耗费的金额。那么就是最小生成树的题目,首先将第一个节点放入temp数组,然后看哪个节点离他的费用最少,再将最少费用的节点放入temp数组中。不断比对,不存在于temp数组中且与temp数组中节点距离最短的节点,放入temp数组,并不断累加金额。最后输出地金额,就是路所需的最小维护金额。
#include<iostream>
#include<stdio.h>
#include<string>
#include<climits>
using namespace std;
void prim(int a[100][100],int n)
{
int sum=0;
int *temp=new int[n];
int index=-1;
temp[++index]=0;
while(index<n-1)
{
int min=INT_MAX;
int t=INT_MAX;
for(int i=0;i<=index;i++)
{
for(int j=1;j<n;j++)
{
bool tag=true;
for(int k=0;k<=index;k++)
{
if(j==temp[k])
{
tag=false;
break;
}
}
if(tag)
{
if(a[temp[i]][j]!=-1&&a[temp[i]][j]<min)
{
min=a[temp[i]][j];
t=j;
}
}
}
}
temp[++index]=t;
sum+=min;
}
cout<<sum<<endl;
}
int main()
{
int n,a[100][100];
cin>>n;
while(n!=0)
{
for(int i=0;i<100;i++)
{
for(int j=0;j<100;j++)
{
a[i][j]=-1;
}
}
for(int i=0;i<n-1;i++)
{
char temp1;
int temp2;
cin>>temp1;
cin>>temp2;
//cout<<temp1<<" "<<temp2<<endl;
for(int j=0;j<temp2;j++)
{
char temp3;
int temp4;
cin>>temp3;
cin>>temp4;
//cout<<temp3<<" "<<temp4<<endl;
a[temp1-'A'][temp3-'A']=temp4;
a[temp3-'A'][temp1-'A']=temp4;
}
getchar();
}
prim(a,n);
cin>>n;
}
system("pause");
return 0;
}