现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。
输入格式说明:
输入数据包括城镇数目正整数N(<=1000)和候选道路数目M(<=3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。
输出格式说明:
输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出-1,表示需要建设更多公路。
样例输入与输出:
序号 | 输入 | 输出 |
1 | 6 15 1 2 5 1 3 3 1 4 7 1 5 4 1 6 2 2 3 4 2 4 6 2 5 2 2 6 6 3 4 6 3 5 1 3 6 1 4 5 10 4 6 8 5 6 3 | 12 |
2 | 3 1 2 3 2 | -1 |
3 | 5 4 1 2 1 2 3 2 3 1 3 4 5 4 | -1 |
——————————————————
这个题目的代码量很大,先传张上课的课件。
这就是Prim算法,和Dijkstra算法有一定的区别。
本题首相经过DFS查找是否为连通图,然后Prim算法进行找到路径。
还是Prim算法不太熟悉,也没有深度理解。
代码如下。
#include <iostream>
#include <stdlib.h>
#include <memory.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define MAX 100000
#define min( a, b) (a)<(b)?(a):(b)
int N=0,M=0;
typedef struct Graph
{
int matrix[1010][1010];
bool visited[1010];
// int vNum;
}* pGraph;
int cost[3010];
bool used[3010];
pGraph g;
void Creat()
{
g=(pGraph)malloc(sizeof(struct Graph));
// g->vNum=N;
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
g->matrix[i][j]=MAX;
}
cost[i]=MAX;
g->visited[i]=false;
}
for(int i=0; i<M; i++)
{
int c1,c2,c;
cin>>c1>>c2>>c;
g->matrix[c1-1][c2-1]=g->matrix[c2-1][c1-1]=c;//
}
}
void DFS(int v)
{
if(g->visited[v]) return;
g->visited[v]=true;
for(int i=0; i<N; i++)
{
if(!g->visited[i] && g->matrix[v][i] != MAX)
{
DFS(i);
}
}
}
int Prim()
{
int res=0;
for(int j=0; j<N; j++)
{
// cost[j]=g->matrix[0][j];
cost[j]=MAX;
used[j]=false;
}
cost[0]=0;
while(1)
{
int pos=-1;
for(int i=0; i<N; i++)
{
if(!used[i] && (pos==-1 || cost[i]<cost[pos]))
{
pos=i;
}
}
if(pos==-1) break;
used[pos]=true;
res+=cost[pos];
for(int i=0; i<N; i++)
{
cost[i]=min(cost[i],g->matrix[pos][i]);
}
}
return res;
// for(int i=1; i<N; i++)
// {
// for(j=1; j<N; j++)
// {
// if(cost[j]!=0 && min>cost[j])
// {
// min=cost[j];
// pos=j;//ÕÒµ½×îСµÄλÖÃ
// }
// }
// if(pos == -1)//ûÓÐÕÒµ½
// {
// break;
// }
// res+=cost[pos];
// cost[pos]=0;
// for(j=1; j<N; j++)
// {
// if(cost[j] !=0 && g->matrix[pos][j]<cost[j])
// {
// cost[j]=g->matrix[pos][j];
// }
// }
// }
// return res;
}
void printg()
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
cout<<g->matrix[i][j]<<" ";
}
// cout<<g->visited[i];
cout<<endl;
}
}
int main(int argc, char** argv) {
int ans;
cin>>N>>M;
Creat();
// printg();
DFS(0);
for(int i=0; i<N; i++)
{
if(!g->visited[i])
{
cout<<-1<<endl;
return 0;
}
}
ans=Prim();
cout<<ans<<endl;
return 0;
}