poj 2075(prim 算法)

题目链接:点击打开链接

题目分析:最小生成树的小题目,适合练手

题目总结:

。。。小心啊写成“%1.f”一直出不来= =

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define MAXN 1000
#define INF 1000000000
using namespace std;
string data[MAXN];
float grid[MAXN][MAXN],cable;//cable is the maxi


bool comp(string a,string b)
{
    int len_a=a.length(),len_b=b.length();
    if(len_a!=len_b) return false;
    for(int i=0;i<len_a;i++)
    {
        if(a[i]!=b[i]) return false;
    }
    return true;
}
int find_loc(string a,int n)
{
    for(int i=1;i<=n;i++)
    {
        if(1==operator==(a,data[i]))
        return i;
    }
}
float ans;
void prim(int n)
{

    int close[MAXN],i,u,num=1,merge;
    float lowcost[MAXN],min_dis;
    for(i=1;i<=n;i++)
    {
        lowcost[i]=INF,close[i]=0;
    }
    u=1;ans=0;close[1]=-1;
    while(1)
    {
        if(num==n)
          break;
        min_dis=INF;
        for(u =1;u<=n;u++)//多加了一成循环在【u】中找    
        {
            if(close[u]==-1)
            {
            for(i=1;i<=n;i++)
            {

            if(close[i]!=-1&&grid[u][i]+1.0>1e-8)//判断是否有边
            {

                double tmp=grid[u][i];
                if(tmp<lowcost[i])
                lowcost[i]=tmp;
                 if(lowcost[i]<min_dis)
                 {
                     merge=i;
                     min_dis=lowcost[i];
                 }
            }
            }

            }
        }

        ans+=min_dis;close[merge]=-1;
       num++;
    }
}
int main()
{
    freopen("in.txt","r",stdin);
    int n,m,i,a,b;
    string x,y;
    float dis;
    while(scanf("%f",&cable)!=EOF)
    {
        scanf("%d",&n);
        getchar();
        for(i=1;i<=n;i++)
            getline(cin,data[i]);
        scanf("%d",&m);
        for(i=1;i<=n;i++)     //用memset 的效果一样
          for(int j=1;j<=n;j++)
            grid[i][j]=-1.0;

        for(i=1;i<=m;i++)
        {
            getchar();
            getline(cin,x,' ');//c++对getline不接受,会ce
            getline(cin,y,' ');
            scanf("%f",&dis);
            a = find_loc(x,n); b = find_loc(y,n);

            grid[a][b]=grid[b][a]=dis;
        }

        prim(n);

        if(ans>cable) printf("Not enough cable\n");
        else printf("Need %.1f miles of cable\n",ans);//。。。小心啊写成“%1.f”一直出不来= =
    }
    return 0;
}


阅读更多
个人分类: ACM_poj ACM_图论
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭