九度题目1154:Jungle Roads

来源:互联网 发布:上海人工智能公司排名 编辑:程序博客网 时间:2024/06/03 17:02

纪念一下最小生成树和我的渣渣水平

九度题目1154:Jungle Roads

#include<stdio.h>#include<iostream>#include<vector>#include<string.h>#include<queue>using namespace std;int n,m;struct edge{    int to;    int d;    friend bool operator < (const edge &a,const edge &b)    {        if(a.d>b.d)            return true;        return false;    }};vector<edge>G[30];vector<edge>::iterator ite;priority_queue<edge>q;bool vis[100];char c;char tmp;int dis;int prim(){    int dis = 0;    edge e;    e.to =0;    e.d = 0;    q.push(e);    while(!q.empty())    {        e = q.top();        //cout<<e.to<<endl;        while(1)        {            if(vis[e.to]==0)                break;            //cout<<"--"<<endl;            if(q.empty())            {                e.d = 0;                break;                //cout<<"breakl"<<endl;            }            q.pop();            e=q.top();        }        vis[e.to]=1;//        cout<<e.to<<endl;//        cout<<e.d<<endl;        dis += e.d;        for(ite = G[e.to].begin();ite!=G[e.to].end();ite++)        {            edge ee ;            ee = *ite;           // cout<<ee.to<<endl;           if(!vis[ee.to])            q.push(ee);        }    }   // cout<<"--"<<endl;    return dis;}int main(){    while(~scanf("%d",&n)&&n)    {        for(int i = 0 ; i <= n;i++)        G[i].clear();        memset(vis,0,sizeof(vis));        for(int i = 1 ; i < n ;i++)        {            getchar();            scanf("%c",&c);            scanf("%d",&m);            for(int j = 0 ; j < m ;j++)            {                //                getchar();                scanf("%c",&tmp);                //cout<<tmp<<" ";                scanf("%d",&dis);                //cout<<dis<<endl;                edge e;                e.to = tmp-'A';                e.d = dis;                G[c-'A'].push_back(e);                e.to = c-'A';                G[tmp-'A'].push_back(e);            }        }//        cout<<"---"<<endl;        cout<<prim()<<endl;    }}


0 0