ZOJ 2048(Prim 或者 Kruskal)

Highways


Time Limit: 5 Seconds      Memory Limit: 32768 KB      Special Judge


The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the most important towns. However, there are still some towns that you can‘t reach via a highway. It is necessary to build more highways so that it will be possible to drive between any pair of towns without leaving the highway system.

Flatopian towns are numbered from 1 to N and town i has a position given by the Cartesian coordinates (xi, yi). Each highway connects exaclty two towns. All highways (both the original ones and the ones that are to be built) follow straight lines, and thus their length is equal to Cartesian distance between towns. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways.

The Flatopian government wants to minimize the cost of building new highways. However, they want to guarantee that every town is highway-reachable from every other town. Since Flatopia is so flat, the cost of a highway is always proportional to its length. Thus, the least expensive highway system will be the one that minimizes the total highways length.

Input

The input consists of two parts. The first part describes all towns in the country,
and the second part describes all of the highways that have already been built.

The first line of the input contains a single integer N (1 <= N <= 750),
representing the number of towns. The next N lines each contain two integers,
xi and yi separated by a space. These values give the coordinates of ith town
(for i from 1 to N). Coordinates will have an absolute value no greater than
10000. Every town has a unique location.

The next line contains a single integer M (0 <= M <= 1000), representing
the number of existing highways. The next M lines each contain a pair of integers
separated by a space. These two integers give a pair of town numbers which are
already connected by a highway. Each pair of towns is connected by at most one
highway.

Output

Write to the output a single line for each new highway that should be built
in order to connect all towns with minimal possible total length of new highways.
Each highway should be presented by printing town numbers that this highway
connects, separated by a space.

If no new highways need to be built (all towns are already connected), then
the output should be created but it should be empty.


This problem contains multiple test cases!

The first line of a multiple input is an integer N, then a blank line followed
by N input blocks. Each input block is in the format indicated in the problem
description. There is a blank line between input blocks.

The output format consists of N output blocks. There is a blank line between
output blocks.


Sample Input

1

9
1 5
0 0
3 2
4 5
5 1
0 4
5 2
1 2
5 3
3
1 3
9 7
1 2

Sample Output

1 6
3 7
4 9
5 7
8 3

收获:第一次用prim,了解了下prim模板。

方法1:prim

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
using namespace std;

const int INF=0x3f3f3f3f;
const double eps=1e-10;
const double PI=acos(-1.0);
#define maxn 1000
struct Node
{
    int x, y;
};
Node node[maxn];
int vis[maxn];
int n;
int dis[maxn];
int pre[maxn];
int map1[maxn][maxn];
void Prim(){
    int i,j,k,tmp,ans;
    memset(vis, 0, sizeof vis);
    for(i=1;i<=n;i++)
    {
        dis[i] = INF;
        pre[i] = 1;
    }
    dis[1]=0;
    vis[1]=1;
    for(i=1;i<=n;i++){
        tmp=INF; k=1;
        for(j=1;j<=n;j++){
            if(!vis[j]&&tmp>dis[j]){
                tmp=dis[j];
                k=j;
            }//找出最小距离的节点
        }
        vis[k]=1;//把访问的节点做标记
        for(j=1;j<=n;j++){
            if(!vis[j]&&dis[j]>map1[k][j])
            {
                dis[j]=map1[k][j];
                pre[j]=k;
            }//更新与k相邻的最短距离
        }
    }
    for(int i = 2; i <= n; i++)
    {
        if(map1[pre[i]][i] != 0)
        {
            printf("%d %d\n",i, pre[i]);
        }
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
        scanf("%d%d", &node[i].x, &node[i].y);
        int a, b;
        int m;
        scanf("%d", &m);
        for(int i = 1; i <= n ; i++)
            for(int j = i+1; j <= n; j++)
            map1[i][j] = map1[j][i] = (node[i].x - node[j].x)*(node[i].x - node[j].x) + (node[i].y - node[j].y)*(node[i].y - node[j].y);
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d", &a, &b);
            map1[a][b] = map1[b][a] = 0;
        }
        Prim();
        if(t)
            puts("");
    }
    return 0;
}

2.Kruskal

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
using namespace std;

const int INF=0x3f3f3f3f;
const double eps=1e-10;
const double PI=acos(-1.0);
#define maxn 570000
struct Node
{
    int x, y;
};
Node node[maxn];
struct Edge
{
    int u, v ,w;
    bool operator < (const Edge &a) const
    {
        return w < a.w;
    }
};
Edge edge[maxn];
int root[maxn];
int num;
void addedge(int u, int v)
{
    edge[num].u = u;
    edge[num].v = v;
    edge[num].w = (node[u].x - node[v].x)*(node[u].x - node[v].x) + (node[u].y - node[v].y)*(node[u].y - node[v].y);
    num++;
}
int n;
void init_root()
{
    for(int i = 1; i <= n; i++)
        root[i] = i;
}
int find_root(int x)
{
    int k,j,r;
    r=x;
    while(r!=root[r])
        r=root[r];
    k=x;
    while(k!=r)
    {
        j=root[k];
        root[k]=r;
        k=j;
    }
    return r;
}
void uni(int a, int b)
{
    int x = find_root(a);
    int y = find_root(b);
     //printf("%d %d\n", x, y);
    if(x == y)
        return;
    else
        root[y] = x;
}
int cnt;
void solve()
{
    for(int i = 0; i < num; i++)
    {
        int u = find_root(edge[i].u);
        int v = find_root(edge[i].v);

        if(u != v)
        {
            root[v] = u;
            cnt++;
            printf("%d %d\n", edge[i].u, edge[i].v);
        }
        if(cnt == n-1)
            break;
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
      scanf("%d", &n);
           for(int i = 1; i <= n; i++)
            scanf("%d%d", &node[i].x, &node[i].y);
        int a, b;
        num = 0;
        int m;
        scanf("%d", &m);
        cnt = 0;
        init_root();
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d", &a, &b);
            if(find_root(a) != find_root(b))
            {
                cnt++;
                uni(a, b);
            }
        }
        for(int i = 1; i <= n ; i++)
            for(int j = i+1; j <= n; j++)
            addedge(i, j);
        sort(edge, edge+num);
        solve();
        if(t)
            puts("");
    }
    return 0;
}
时间: 2024-11-05 17:33:14

ZOJ 2048(Prim 或者 Kruskal)的相关文章

ZOJ 2048 Highways

kruskal实现 1 #include<iostream> 2 #include<cmath> 3 #include<algorithm> 4 #include<cstdio> 5 using namespace std; 6 #define maxn 760 7 int par[maxn]; 8 int pos; 9 int n,m; 10 struct node 11 { 12 int x; 13 int y; 14 double w;//!可以不开方

Prim和Kruskal最小生成树

标题: Prim和Kruskal最小生成树时 限: 2000 ms内存限制: 15000 K总时限: 3000 ms描述: 给出一个矩阵,要求以矩阵方式单步输出生成过程.要求先输出Prim生成过程,再输出Kruskal,每个矩阵输出后换行.注意,题中矩阵表示无向图输入: 结点数矩阵输出: Prim:矩阵输出 Kruskal:矩阵输出输入样例: 3 0 1 3 1 0 2 3 2 0 输出样例: 3 0 1 3 1 0 2 3 2 0Prim: 0 0 0 0 0 0 0 0 0 0 1 0 1

【图论】信手拈来的Prim,Kruskal和Dijkstra

关于三个简单的图论算法 prim,dijkstra和kruskal三个图论的算法,初学者容易将他们搞混,所以放在一起了. prim和kruskal是最小生成树(MST)的算法,dijkstra是单源最短路径的算法. prim 最小生成树prim算法采用了贪心策略:把点分成两个集合,A为已被处理(已经在最小生成树中)的顶点,B为待处理的顶点,(A,B)也就是一个割.若边(u,v)满足u∈A,v∈B,那么(u,v)就是通过割(A,B)的一条边. 很自然的,会有一定数量的边会通过该割,其中权重最小的边

最小生成树的两种算法:Prim和Kruskal算法

越来越明白了一个道理:你写不出代码的原因只有一个,那就是你没有彻底理解这个算法的思想!! 以前写过最小生成树,但是,水了几道题后,过了一段时间,就会忘却,一点也写不出来了.也许原因只有一个,那就是我没有彻底理解这两种算法. 主题: 其实,求最小生成树有两个要点,一个是权值最小,还有一个就是这个图必须是树.而Prim和Kruskal的不同之处在于两者选择的变量不同,Prim选择的是始终保持权值最小,然后逐个加点构建一棵树.而Kruskal则是始终保证是一棵树(虽然构建过程中不一定是真正的树,但并查

zoj 1203 Swordfish (kruskal 克鲁斯卡尔)

Swordfish Time Limit: 2 Seconds      Memory Limit: 65536 KB There exists a world within our world A world beneath what we call cyberspace. A world protected by firewalls, passwords and the most advanced security systems. In this world we hide our dee

Prim和Kruskal求最小生成树

Prim: 算法步骤: 1.任意结点开始(不妨设为v1)构造最小生成树: 2.首先把这个结点(出发点)包括进生成树里, 3.然后在那些其一个端点已在生成树里.另一端点还未在生成树里的所有边中找出权最小的一条边, 4.并把这条边.包括不在生成树的另一端点包括进生成树, …. 5.依次类推,直至将所有结点都包括进生成树为止 Pascal的渣渣代码... 注:寻找最短的边那一步可以用堆优化,但那样还不如直接用Kruskal...... Reference: http://www.nocow.cn/in

最小生成树 - Prim 和Kruskal

最近有些忙,先把最小生成树的代码挂上,有时间将讲解补上. 在这里两个函数:Prim和Kruskal函数,分别是这两个算法的主算法代码.使用的图存储方式是邻接矩阵. #include<iostream> #include<string.h> #include<queue> using namespace std; #define MAX 100 #define INT_MAX 10000 #define min(x,y)(x<y?x:y) typedef struc

HDU 3080 The plan of city rebuild(prim和kruskal)

The plan of city rebuild Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 616    Accepted Submission(s): 215 Problem Description News comes!~City W will be rebuilt with the expectation to become

【裸MST:prim+邻接矩阵 / Kruskal+邻接表】hdu 1233 还是畅通工程

Source : hdu 1233 还是畅通工程 http://acm.hdu.edu.cn/showproblem.php?pid=1233 Problem Description 某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离.省政府"畅通工程"的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小.请计算最小的公路总长度. Input 测试输入包含若干测试用例.每个测试用例的第1行给出村庄