F - alive series to find the most perfect life (minimum spanning tree)

Description

Perhaps, people live is to try ups and downs of this world, emotions, through a process from infants to the elderly it! You can see, to think, to love, to hate, which is the difference between the living and the dead. Do not think about what will happen after death, no one knows. So to live good, pardon himself, cherish the people around!
Now, the hand of God forgive you. All the ups and downs in your life to be experienced all put in front of you. You need to experience life n kinds of things. Each thing has a weight x. God gave you the n-1 time tunnel. You can put a time tunnel in the middle of any two things, if you put the time tunnel on a, middle b, then you need to spend 3 * (xa + xb) +7 . Now you need to put the n-1 even in the middle of a time tunnel n kinds of things, so that any two things are connected, and the cost to a minimum. Output minimum cost.
Input

First enter a number T, T representatives of groups of data.
Enter a next line number n.
The next line number of inputs n, the i-th weight of the i-th representative of things.
n <= 1000, the weight of each thing <= 100000;
T <= 60
the Output

T output lines, each output minimum cost.
Sample

Input

1
2
1 2
Output

16

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define INF 0x3f3f3f3f
int dis[1010],vis[1100];
int Map[1100][1100];
int n;
int prim()
{
    int sum = 0;
    for(int i=1; i<=n; i++)
    {
        dis[i] = Map[1][i];
    }
    vis[1] = 1;
    for(int i=2; i<=n; i++)
    {
        int flag;
        int Min = INF;
        for(int j=1; j<=n; j++)
        {
            if(!vis[j]&&dis[j]<Min)
            {
                Min = dis[j];
                flag = j;
            }
        }
        vis[flag] = 1;
        sum += Min;
        for(int j=1; j<=n; j++)//本题的思路其实就是当做每个点与其他点之间都连通,然后求出两点之间权值后求最小生成树
        {
            if(!vis[j]&&dis[j]>Map[flag][j])
            {
                dis[j] = Map[flag][j];
            }
        }
    }
    return sum;
}
int main()
{
    int t;
    int a[1101];
    scanf("%d",&t);
    int u,v,w;
    while(t--)
    {
        scanf("%d",&n);
        memset(vis,0,sizeof(vis));
        memset(Map,INF,sizeof(Map));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        for(int i=1;i<=n;i++)
        {
            for(int j=i+1;j<=n;j++)
            {
                w = 3*(a[i]+a[j])+7;
                Map[i][j] = Map[j][i] = w;
            }
        }
        printf("%d\n",prim());
    }
    return 0;
}


Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104917683