题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1301
方法:直接建模后用prim算法
感想:简单题
代码:
#include<iostream> #include <queue> using namespace std; struct fuckNode { int index; int distance; }; struct cmp { bool operator ()(fuckNode x, fuckNode y) { return x.distance> y.distance; // x小的优先级高 } }; int main() { int nodeCount = 0; int matrix[26][26]; bool nodesVisited[26]; while(scanf("%d",&nodeCount) && nodeCount!=0) { for(int k=0;k<nodeCount;k++) { nodesVisited[k]=false; for(int w=0;w<nodeCount;w++) matrix[k][w] = 101; } priority_queue<fuckNode, vector<fuckNode>, cmp>q; fuckNode fn; fn.index = 0; fn.distance = 0; q.push(fn); int i =0; char destiny; int arcCost; char source; int arcCount=0; while(i<nodeCount-1) { scanf("%*c%c %d",&source,&arcCount);//注意这里的输入要处理 要清除掉上次产生的输入的最后一个回车 int j =0; while(j<arcCount) { scanf("%*c%c %d",&destiny,&arcCost);//同上 if(arcCost<matrix[source-65][destiny-65]) matrix[destiny-65][source-65]=matrix[source-65][destiny-65] = arcCost; j++; } i++; } int sum = 0; while(!q.empty()) { fuckNode u = q.top(); q.pop(); if(!nodesVisited[u.index]) { nodesVisited[u.index]=true; sum +=u.distance; for(int k =0;k<nodeCount;k++) { if(matrix[u.index][k]<=100 && !nodesVisited[k]) { fuckNode fnn ; fnn.index =k; fnn.distance = matrix[u.index][k]; q.push(fnn); } } } } cout<<sum<<endl; } return 0; }