最小生成树

Prim模板一(书上):

#define MAXV 1005
#define INF 0x3f3f3f3f
int map[1005][1005];
int n,minn=0;
void prim(int t)
{
    int lowcost[MAXV];
    int closet[MAXV];
    int i,j,k;
    for(i=0;i<n;i++)
    {
        lowcost[i]=map[t][i];
        closet[i]=t;
    }
    for(i=1;i<n;i++)
    {
        int minds=INF;
        for(j=0;j<n;j++)
        {
            if(lowcost[j]!=0&&lowcost[j]<minds)
            {
                minds=lowcost[j];
                k=j;
            }
        }
        lowcost[k]=0;
        minn+=minds;
        printf("满足条件的边(%d,%d),权值为%d\n",closet[k],k,minds);
        for(j=0;j<n;j++)
        {
            if(map[k][j]!=0&&map[k][j]<lowcost[j])
            {
                lowcost[j]=map[k][j];
                closet[j]=k;
            }
        }
    }
}

Prim模板二:

#define MAXV 1005
#define INF 0x3f3f3f3f
int map[1005][1005];
int n,minn=0;
void prim(int t)
{
    int vis[MAXV];
    int closet[MAXV];
    int lowcost[MAXV];
    int i,j,k;
    memset(vis,0,sizeof(vis));
    for(i=0;i<n;i++)
    {
        lowcost[i]=map[t][i];
        closet[i]=t;
    }
    vis[0]=1;
    for(i=1;i<n;i++)
    {
        int minds=INF;
        for(j=0;j<n;j++)
        {
            if(vis[j]==0&&lowcost[j]<minds)
            {
                minds=lowcost[j];
                k=j;
            }
        }
        vis[k]=1;
        if(minds==INF)
            break;
        minn+=minds;
        printf("满足条件的边(%d,%d),权值为%d\n",closet[k],k,minds);
        for(j=0;j<n;j++)
        {
            if(vis[j]==0&&map[k][j]<lowcost[j])
            {
                lowcost[j]=map[k][j];
                closet[j]=k;
            }
        }
    }
}

Kruskal模板一:

typedef struct
{
    int u;
    int v;
    int w;
}Edge;
void Kruskal(MGraph g)
{
    int i,j,u1,v1,sn1,sn2,k;
    int vset[MAXV];
    Edge E[maxsize];
    k=0;
    for(i=0;i<g.n;i++)
        for(j=0;j<g.n;j++)
        if(g.edges[i][j]!=0&&g.edges[i]][j]!=INF)
    {
        E[k].u=i;
        E[k].v=j;
        E[k].w=g.edges[i][j];
        k++;
    }
    insertsort(E,g.e);
    for(i=0;i<g.n;i++)
        vset[i]=i;
    k=1;
    j=0;
    while(k<g.n)
    {
        u1=E[j].u;
        v1=E[j].v;
        sn1=vset[u1];
        sn2=vset[v1];
        if(sn1!=sn2)
        {
            printf("%d %d %d\n",u1,v1,E[j].w);
            k++;
            for(i=0;i<g.n;i++)
            {
                if(vset[i]==sn2)
                    vset[i]=sn1;
            }
        }
        j++;
    }
}

Kruskal模板二:

/*求最小生成数中边的最大权值*/
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN =2100;
const int MAXM =40040;
struct EdgeNode
{
    int from;
    int to;
    int w;
}Edges[MAXM];//至少需是点个数的平方
int father[MAXN];
int find(int x)
{
    if(x != father[x])
        father[x] = find(father[x]);
    return father[x];
}
int cmp(EdgeNode a,EdgeNode b)
{
    return a.w < b.w;
}
void Kruskal(int n,int m)
{
    sort(Edges,Edges+m,cmp);
    int Count = 0, maxx = 0;
    for(int i = 0; i < m; ++i)
    {
        int u = find(Edges[i].from);
        int v = find(Edges[i].to);
        if(u!=v)
        {
            father[v] = u;
            Count++;
            if(maxx < Edges[i].w)
                maxx = Edges[i].w;  ///求最小生成树时累加即可
            if(Count == n-1)
                break;
        }
    }
    printf("%d\n",maxx);
}
int main(){
    int n,m;//这里n是点的个数,m是边的个数
    while(~scanf("%d%d",&n,&m)){
          for(int i=0;i<n;i++)
            father[i]=i;
         for(int i=0;i<m;i++){
            scanf("%d%d%d",&Edges[i].from,&Edges[i].to,&Edges[i].w);
        }
       Kruskal(n,m);
    }
}

Building a Space Station
题目来源
Description

You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.

All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor’, or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.

You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.

You can ignore the width of a corridor. A corridor is built between points on two cells’ surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input

The input consists of multiple data sets. Each data set is given in the following format.

n
x1 y1 z1 r1
x2 y2 z2 r2

xn yn zn rn

The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.

The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.

Each of x, y, z and r is positive and is less than 100.0.

The end of the input is indicated by a line containing a zero.
Output

For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.

Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Sample Input

3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Sample Output

20.000
0.000
73.834
Source

Japan 2003 Domestic

裸最小生成树
用Prim算法解:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#define INF 0x3f3f3f3f
double map[102][102];
int vis[102];
int n;
double minn;
void prim()
{
    double lowcost[102];
    int closet[102];
    int i,j,k;
    double minds;
    for(i=0;i<n;i++)
    {
        lowcost[i]=map[0][i];
        closet[i]=0;
    }
    vis[0]=1;
    for(i=1;i<n;i++)
    {
        minds=INF;
        for(j=0;j<n;j++)
        {
            if(vis[j]==0&&lowcost[j]<minds)
            {
                minds=lowcost[j];
                k=j;
            }
        }
        minn+=minds;
        vis[k]=1;
        for(j=0;j<n;j++)
        {
            if(vis[j]==0&&map[k][j]<lowcost[j])
            {
                lowcost[j]=map[k][j];
                closet[j]=k;
            }
        }
    }
}
int main()
{

    while(scanf("%d",&n),n!=0)
    {
        memset(vis,0,sizeof(vis));
        int i,j,k;
        for(i=0;i<n;i++)
            for(j=0;j<n;j++)
        {
            if(i==j)
                map[i][j]=0;
            else
            {
                map[i][j]=INF;
                map[j][i]=INF;
            }
        }
        double x[102],y[102],z[102],r[102];
        scanf("%lf %lf %lf %lf",&x[0],&y[0],&z[0],&r[0]);
        for(i=1;i<n;i++)
        {
            scanf("%lf %lf %lf %lf",&x[i],&y[i],&z[i],&r[i]);
            for(j=0;j<i;j++)
            {
                double d=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])+(z[i]-z[j])*(z[i]-z[j]));
                if(d<r[i]+r[j])
                {
                    map[i][j]=0;
                    map[j][i]=0;
                }
                else
                {
                    map[i][j]=d-(r[i]+r[j]);
                    map[j][i]=d-(r[i]+r[j]);
                }
            }
        }
        minn=0;
        prim();
        printf("%.3lf\n",minn);
    }
    return 0;
}

用Kruskal算法解:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<math.h>
using namespace std;
#define MAXM 0x3f3f3f3f
int m,n,flag,k;
double map[112][112],minn;
struct EdgeNode
{
    int from;
    int to;
    double w;
}Edges[100005];//最多100个村庄,这个地方至少是100的平方,这个地方要注意
int father[112];//并查集数组
int find(int x)//判断是否在一个集合,是否会构成重边
{
    if(x != father[x])
        father[x] = find(father[x]);
    return father[x];
}
bool cmp(EdgeNode a,EdgeNode b)//按权值从小到大排列
{
    return a.w < b.w;
}
void Kruskal()
{
    sort(Edges,Edges+k,cmp);
    int Count = 0;
    for(int i=0;i<k;i++)
        father[i]=i;
    for(int i = 0; i < k; ++i)
    {
        double maxx = MAXM;
        int u = find(Edges[i].from);
        int v = find(Edges[i].to);
        if(u!=v)
        {
            father[v] = u;
            Count++;
            if(maxx > Edges[i].w)
            {
                maxx = Edges[i].w;///求最小生成树时累加即可
                minn+=maxx;
            }
            if(maxx==MAXM)
            {
                flag=1;
                printf("0.000\n");
                break;
            }
        }
        if(Count == n-1)
            break;
    }
}
int main()
{
    while(scanf("%d",&n),n!=0)
    {
        int i,j;
        k=0;
        for(i=0;i<n;i++)
          Edges[i].w=0;
        double x[112],y[112],z[112],r[112];
        scanf("%lf %lf %lf %lf",&x[0],&y[0],&z[0],&r[0]);
        for(i=1;i<n;i++)
        {
            scanf("%lf %lf %lf %lf",&x[i],&y[i],&z[i],&r[i]);
            for(j=0;j<i;j++)
            {
                double d=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])+(z[i]-z[j])*(z[i]-z[j]));
                if(d<r[i]+r[j])
                {
                    Edges[k].from=i;
                    Edges[k].to=j;
                    Edges[k].w=0;
                    k++;
                }
                else
                {
                    Edges[k].from=i;
                    Edges[k].to=j;
                    Edges[k].w=d-(r[i]+r[j]);
                    k++;
                }
            }
        }
        minn=0;
        flag=0;
        Kruskal();
        if(flag==0)
        printf("%.3lf\n",minn);
    }
    return 0;
}

例题:
Jungle Roads
题目来源
Description

The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.

Input

The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, capitalized. Each data set is completed with n-1 lines that start with village labels in alphabetical order. There is no line for the last village. Each line for a village starts with the village label followed by a number, k, of roads from this village to villages with labels later in the alphabet. If k is greater than 0, the line continues with data for each of the k roads. The data for each road is the village label for the other end of the road followed by the monthly maintenance cost in aacms for the road. Maintenance costs will be positive integers less than 100. All data fields in the row are separated by single blanks. The road network will always allow travel between all the villages. The network will never have more than 75 roads. No village will have more than 15 roads going to other villages (before or after in the alphabet). In the sample input below, the first data set goes with the map above.
Output

The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages. Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit.
Sample Input

9
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
3
A 2 B 10 C 40
B 1 C 20
0
Sample Output

216
30
Source

Mid-Central USA 2002
Prim算法

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define INF 52767
int map[30][30];
int n,minn;
void prim()
{
    int lowcost[30];
    int closet[30];
    int i,j,k;
    int minds;
    for(i=0;i<n;i++)
    {
        lowcost[i]=map[0][i];
        closet[i]=0;
    }
    for(i=1;i<n;i++)
    {
        minds=INF;
        for(j=0;j<n;j++)
        {
            if(lowcost[j]!=0&&lowcost[j]<minds)
            {
                minds=lowcost[j];
                k=j;
            }
        }
        //printf("%d %d %d\n",closet[k],k,minds);
        minn+=minds;
        lowcost[k]=0;
        for(j=0;j<n;j++)
        {
            if(map[k][j]!=0&&map[k][j]<lowcost[j])
            {
                lowcost[j]=map[k][j];
                closet[j]=k;
            }
        }
    }
}
int main()
{
    while(scanf("%d",&n),n!=0)
    {
        int i,j,m,a;
        char c[2],cc[2];
        for(i=0; i<30; i++)
        for(j=0; j<30; j++)
        {
            if(i==j)
                map[i][j]=0;
            else
                map[i][j]=INF;
        }
        for(i=1;i<n;i++)
        {
            scanf("%s%d",cc,&m);
            for(j=0; j<m; j++)
            {
                scanf("%s%d",c,&a);
                if(map[cc[0]-'A'][c[0]-'A']>a)
                {
                    map[cc[0]-'A'][c[0]-'A']=a;
                    map[c[0]-'A'][cc[0]-'A']=a;
                }
            }
        }
        minn=0;
        prim();
        printf("%d\n",minn);
    }
    return 0;
}

Networking
题目来源
Description

You are assigned to design network connections between certain points in a wide area. You are given a set of points in the area, and a set of possible routes for the cables that may connect pairs of points. For each possible route between two points, you are given the length of the cable that is needed to connect the points over that route. Note that there may exist many possible routes between two given points. It is assumed that the given possible routes connect (directly or indirectly) each two points in the area.
Your task is to design the network for the area, so that there is a connection (direct or indirect) between every two points (i.e., all the points are interconnected, but not necessarily by a direct cable), and that the total length of the used cable is minimal.
Input

The input file consists of a number of data sets. Each data set defines one required network. The first line of the set contains two integers: the first defines the number P of the given points, and the second the number R of given routes between the points. The following R lines define the given routes between the points, each giving three integer numbers: the first two numbers identify the points, and the third gives the length of the route. The numbers are separated with white spaces. A data set giving only one number P=0 denotes the end of the input. The data sets are separated with an empty line.
The maximal number of points is 50. The maximal length of a given route is 100. The number of possible routes is unlimited. The nodes are identified with integers between 1 and P (inclusive). The routes between two points i and j may be given as i j or as j i.
Output

For each data set, print one number on a separate line that gives the total length of the cable used for the entire designed network.
Sample Input

1 0

2 3
1 2 37
2 1 17
1 2 68

3 7
1 2 19
2 3 11
3 1 7
1 3 5
2 3 89
3 1 91
1 2 32

5 7
1 2 5
2 3 7
2 4 8
4 5 11
3 5 10
1 5 6
4 2 12

0
Sample Output

0
17
16
26
Source

Southeastern Europe 2002
最小生成树 Prim算法

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define INF 52767
int map[52][52];
int n,m,minn;
void prim()
{
    int lowcost[52];
    int closet[52];
    int i,j,k;
    int minds;
    for(i=0;i<m;i++)
    {
        lowcost[i]=map[0][i];
        closet[i]=0;
    }
    for(i=1;i<m;i++)
    {
        minds=INF;
        for(j=0;j<m;j++)
        {
            if(lowcost[j]!=0&&lowcost[j]<minds)
            {
                minds=lowcost[j];
                k=j;
            }
        }
        //printf("%d %d %d\n",closet[k],k,minds);
        minn+=minds;
        lowcost[k]=0;
        for(j=0;j<m;j++)
        {
            if(map[k][j]!=0&&map[k][j]<lowcost[j])
            {
                lowcost[j]=map[k][j];
                closet[j]=k;
            }
        }
    }
}
int main()
{
    while(scanf("%d",&m),m!=0)
    {
        scanf("%d",&n);
        int i,j,a,p,q;
        for(i=0; i<50; i++)
            for(j=0; j<50; j++)
            {
                if(i==j)
                    map[i][j]=0;
                else
                    map[i][j]=INF;
            }
        for(i=0;i<n;i++)
          {
              scanf("%d %d %d",&p,&q,&a);
              if(map[p-1][q-1]>a)
              {
                  map[p-1][q-1]=a;
                  map[q-1][p-1]=a;
              }
          }
        if(n==0)
          printf("0\n");
        else
        {
            minn=0;
            prim();
            printf("%d\n",minn);
        }
    }
    return 0;
}

Constructing Roads
题目来源
Description
There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
Input
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
Output
You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.
Sample Input
3
0 990 692
990 0 179
692 179 0
1
1 2
Sample Output
179

最小生成树Prim算法
将已经连通的路长度置为零
代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define INF 52767
int map[102][102],vis[102];
int n,m,minn;
void prim()
{
    int lowcost[102];
    int closet[102];
    int i,j,k;
    int minds;
    for(i=0;i<m;i++)
    {
        lowcost[i]=map[0][i];
        closet[i]=0;
    }
    vis[0]=1;
    for(i=1;i<m;i++)
    {
        minds=INF;
        for(j=0;j<m;j++)
        {
            if(vis[j]==0&&lowcost[j]<minds)
            {
                minds=lowcost[j];
                k=j;
            }
        }
        minn+=minds;
        vis[k]=1;
        for(j=0;j<m;j++)
        {
            if(vis[j]==0&&map[k][j]<lowcost[j])
            {
                lowcost[j]=map[k][j];
                closet[j]=k;
            }
        }
    }
}
int main()
{
    memset(vis,0,sizeof(vis));
    scanf("%d",&m);
    int i,j,x,y;
    for(i=0;i<m;i++)
    {
        for(j=0;j<m;j++)
        scanf("%d",&map[i][j]);
    }
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d %d",&x,&y);
        map[x-1][y-1]=0;
        map[y-1][x-1]=0;
    }
    minn=0;
    prim();
    printf("%d\n",minn);
    return 0;
}

未完待续。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值