最小生成树

Ice_cream’s world III

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2660    Accepted Submission(s): 938


 

Problem Description

ice_cream’s world becomes stronger and stronger; every road is built as undirected. The queen enjoys traveling around her world; the queen’s requirement is like II problem, beautifies the roads, by which there are some ways from every city to the capital. The project’s cost should be as less as better.

 

 

Input

Every case have two integers N and M (N<=1000, M<=10000) meaning N cities and M roads, the cities numbered 0…N-1, following N lines, each line contain three integers S, T and C, meaning S connected with T have a road will cost C.

 

 

Output

If Wiskey can’t satisfy the queen’s requirement, you must be output “impossible”, otherwise, print the minimum cost in this project. After every case print one blank.

 

 

Sample Input

 

2 1 0 1 10 4 0

 

 

Sample Output

 

10 impossible

 

 

Author

Wiskey

模板题 但是这道题有点小坑 哇了两发 结果发现是重边问题!!!

重边要选个最小的权值录入

#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
#define  LL long long
#define  ULL unsigned long long
#define mod 1000000007
#define INF 0x7ffffff
#define mem(a,b) memset(a,b,sizeof(a))
#define MODD(a,b) (((a%b)+b)%b)
using namespace std;
const int maxn=1005;
int G[maxn][maxn];
int d[maxn];
int vis[maxn];
int cot=0;
int ans;
int n,m;
int prim()
{
    mem(vis,0);
    fill(d,d+maxn,INF);
    d[0]=0;
    ans=0;
    for(int i=0;i<n;i++){
        int u=-1,Min=INF;
        for(int j=0;j<n;j++){
            if(d[j]<Min&&!vis[j]){
                Min=d[j];
                u=j;
            }
        }
        if(u==-1) return -1;
        vis[u]=1;
        ans+=d[u];
        for(int v=0;v<n;v++){
            if(!vis[v]&&G[u][v]!=INF&&G[u][v]<d[v])
                d[v]=G[u][v];
        }
    }

    return ans;
}
int main()
{

    while(~scanf("%d%d",&n,&m)){
        fill(G[0],G[0]+maxn*maxn,INF);
        for(int i=0;i<m;i++){
            int a,b,val;
            scanf("%d%d%d",&a,&b,&val);
            if(val<G[a][b])
            G[a][b]=G[b][a]=val;
        }
        int sum=prim();
        if(sum!=-1) printf("%d\n\n",sum);
        else printf("impossible\n\n");
    }



    return 0;


}






 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值