Chapter9——图——最小生成树

1. 题目列表

  • POJ1789(prim算法)
  • POJ2485(prim)
  • POJ1258(prim)
  • POJ3026(BFS+prim)

2. POJ1789——Truck History

2.1 题目描述

Description

Advanced Cargo Movement, Ltd. uses trucks of different types. Some trucks are used for vegetable delivery, other for furniture, or for bricks. The company has its own code describing each type of a truck. The code is simply a string of exactly seven lowercase letters (each letter on each position has a very special meaning but that is unimportant for this task). At the beginning of company's history, just a single truck type was used but later other types were derived from it, then from the new types another types were derived, and so on.

Today, ACM is rich enough to pay historians to study its history. One thing historians tried to find out is so called derivation plan -- i.e. how the truck types were derived. They defined the distance of truck types as the number of positions with different letters in truck type codes. They also assumed that each truck type was derived from exactly one other truck type (except for the first truck type which was not derived from any other type). The quality of a derivation plan was then defined as
1/Σ(to,td)d(to,td)

where the sum goes over all pairs of types in the derivation plan such that to is the original type and td the type derived from it and d(to,td) is the distance of the types.
Since historians failed, you are to write a program to help them. Given the codes of truck types, your program should find the highest possible quality of a derivation plan.
Input

The input consists of several test cases. Each test case begins with a line containing the number of truck types, N, 2 <= N <= 2 000. Each of the following N lines of input contains one truck type code (a string of seven lowercase letters). You may assume that the codes uniquely describe the trucks, i.e., no two of these N lines are the same. The input is terminated with zero at the place of number of truck types.
Output

For each test case, your program should output the text "The highest possible quality is 1/Q.", where 1/Q is the quality of the best derivation plan.

Sample Input

4
aaaaaaa
baaaaaa
abaaaaa
aabaaaa
0
Sample Output

The highest possible quality is 1/3.

2.2 解决思路

题意:有n个车子,每个车子有个代码,定义任意两个车子i和j的距离为不同代码的个数,
    并且除了第一辆车,其他车都是由某辆车的代码演化而来,求最小的演化距离。
    
本题即以第一辆车为源点,求最小生成树的路径和。在算法的选择上,由于每一辆车和其他车都会有连接边,
所以是稠密图,选择prim算法。若顶点多,边少,选用克鲁斯卡尔算法。


使用邻接表存储会超内存。。可能维护vector结构所需要的内存过大? 
使用邻接矩阵不会。。 

2.3 代码

#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;

/*
    题意:有n个车子,每个车子有个代码,定义任意两个车子i和j的距离为不同代码的个数,
        并且除了第一辆车,其他车都是由某辆车的代码演化而来,求最小的演化距离。
        
    本题即以第一辆车为源点,求最小生成树的路径和。
    
    使用邻接表存储会超内存。。可能维护vector结构所需要的内存过大? 
    使用邻接矩阵不会。。 
*/
const int maxn = 2001;
const int INF = 1e7;
int g[maxn][maxn];
int d[maxn];
bool visited[maxn];
char code[maxn][8];

int getDist(char c1[], char c2[], int len){
    int sum = 0;
    for (int i = 0; i < len; i++)
        if (c1[i] != c2[i])
            sum++;
    return sum;
}

int Prim(int n){
    int sum = 0;
    fill(visited, visited + maxn, false);
    fill(d, d + maxn, INF);
    d[1] = 0;
    for (int i = 1; i <= n; i++){
        int u = -1, MIN = INF;
        for (int j = 1; j <= n; j++){
            if (!visited[j] && d[j] < MIN){
                MIN = d[j];
                u = j;
            }
        }
        if (u == -1) break;
        sum += MIN;
        visited[u] = true;
        for (int v = 1; v <= n; v++){
            if (g[u][v] != INF && g[u][v] < d[v])
                d[v] = g[u][v];
        }
    }
    return sum;
}

int main(){
    int n;
    while (~scanf("%d", &n) && n){
        fill(g[0], g[0] + maxn * maxn, INF);
        for (int i = 1; i <= n; i++){
            scanf("%s", code[i]);
            // 计算 1~ i - 1号节点与其的距离 
            for (int j = 1; j < i; j++){
                if (i == j) continue;
                int dist = getDist(code[i], code[j], 7);
                g[i][j] = g[j][i] = dist;
            }
        }
        int res = Prim(n);
        printf("The highest possible quality is 1/%d.\n", res);
    }
    return 0;
}

3. POJ3026——Borg Maze

3.1 题目描述

Description

The Borg is an immensely powerful race of enhanced humanoids from the delta quadrant of the galaxy. The Borg collective is the term used to describe the group consciousness of the Borg civilization. Each Borg individual is linked to the collective by a sophisticated subspace network that insures each member is given constant supervision and guidance.

Your task is to help the Borg (yes, really) by developing a program which helps the Borg to estimate the minimal cost of scanning a maze for the assimilation of aliens hiding in the maze, by moving in north, west, east, and south steps. The tricky thing is that the beginning of the search is conducted by a large group of over 100 individuals. Whenever an alien is assimilated, or at the beginning of the search, the group may split in two or more groups (but their consciousness is still collective.). The cost of searching a maze is definied as the total distance covered by all the groups involved in the search together. That is, if the original group walks five steps, then splits into two groups each walking three steps, the total distance is 11=5+3+3.
Input

On the first line of input there is one integer, N <= 50, giving the number of test cases in the input. Each test case starts with a line containg two integers x, y such that 1 <= x,y <= 50. After this, y lines follow, each which x characters. For each character, a space '' stands for an open space, a hash mark#'' stands for an obstructing wall, the capital letter A'' stand for an alien, and the capital letterS'' stands for the start of the search. The perimeter of the maze is always closed, i.e., there is no way to get out from the coordinate of the ``S''. At most 100 aliens are present in the maze, and everyone is reachable.
Output

For every test case, output one line containing the minimal cost of a succesful search of the maze leaving no aliens alive.

Sample Input

2
6 5
##### 
#A#A##
# # A#
#S  ##
##### 
7 7
#####  
#AAA###
#    A#
# S ###
#     #
#AAA###
#####  
Sample Output

8
11

3.2 解决思路

BFS+Prim

  • 首先使用BFS求A或S任意两个点间的最短距离,并使用该距离建图。
  • 使用Prim算法求解最小生成树,经过分析可知,答案就是最小生成树路径和。

此题应注意几个坑点:

    1. 读入含空格的字符数组时,使用gets(char*[])或scanf("%c),不能使用scanf("%s),它是以空格为分界符。
    1. 使用getchar()或gets来过滤字符数组之前的换行符,因为换行符仍然保留在输入缓冲区,需要过滤掉
    1. 注意本题的建图方法:给节点标上序号。
    1. 此题的节点数较少,应选择适合于稀疏图的最小生成树算法Prim算法。
    1. 合理的初始化变量。

3.3 代码

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

struct Node{
    int x, y;
    int step;
};
const int maxn = 110;
const int INF = 1e6;
int g[maxn][maxn], d[maxn], xmax, ymax, hashtable[55][55];
bool visited[maxn], vis[55][55];
char map[55][55];
int X[4] = {-1, 1, 0, 0};
int Y[4] = {0, 0, -1, 1};

// 广搜,计算所有节点的最短距离 
void BFS(Node s){
    memset(vis, false, sizeof(vis));
    int sx = s.x, sy = s.y, step = s.step;
    queue<Node> q;
    q.push(s);
    while (!q.empty()){
        Node node = q.front();
        int x = node.x, y = node.y, step = node.step;
        q.pop();
        if (map[x][y] == 'A' || map[x][y] == 'S'){
            g[hashtable[x][y]][hashtable[sx][sy]] = node.step;
        }
        vis[node.x][node.y] = true;
        for (int i = 0; i < 4; i++){
            int newX = x + X[i];
            int newY = y + Y[i];
            if (!(newX < 0 || newX >= xmax || newY < 0 || newY >= ymax || 
            vis[newX][newY] || map[newX][newY] == '#'
            )){
                Node newNode;
                newNode.x = newX, newNode.y = newY, newNode.step = step + 1;
                q.push(newNode);
            }
        } 
    }
}

int Prim(int s, int n){
    int sum = 0;
    fill(visited, visited + maxn, false);
    fill(d, d + maxn, INF);
    d[s] = 0;
    for (int i = 1; i <= n; i++){
        int u = -1, MIN = INF;
        for (int j = 1; j <= n; j++){
            if (!visited[j] && d[j] < MIN){
                MIN = d[j];
                u = j;
            }
        }
        if (u == -1) break;
        sum += MIN;
        visited[u] = true;
        for (int v = 1; v <= n; v++){
            if (g[u][v] != INF && g[u][v] < d[v])
                d[v] = g[u][v];
        }
    }
    return sum;
}

void output(){
    for (int i = 0; i < xmax; i++){
        printf("%s\n", map[i]);
    }
}

int main(){
    int T;
    scanf("%d", &T);
    while (T--){
        fill(g[0], g[0] + maxn * maxn, INF);
        int n = 1, s;
        scanf("%d%d", &ymax, &xmax);
        gets(map[0]);
        for (int i = 0; i < xmax; i++){
            gets(map[i]);
            for (int j = 0; j < ymax; j++){
                if (map[i][j] == 'S' || map[i][j] == 'A'){
                    // 给节点A或S标号,并记录位置坐标 
                    hashtable[i][j] = n++;
                }
            }
        }
        // 广搜计算各个点之间最小的距离   
        for (int i = 0; i < xmax; i++)
            for (int j = 0; j < ymax; j++){
                if (map[i][j] == 'A' || map[i][j] == 'S'){
                    Node node;
                    node.x = i, node.y = j, node.step = 0;
                    BFS(node);
                }
            } 
        int res = Prim(1, n - 1); // 顶点编号1~n,从任意一个节点开始  
        printf("%d\n", res);
    }
    return 0;
} 

4. 总结

最小生成树问题往往是一个贪心问题,求最小值或最大值,求的是在保证图连通的情况下最小代价。此类题目,应快速准确把握题意,使用Prim或克鲁斯卡尔算法求解。

  • Prim算法可类比Djkstra算法,适用于边密集图,使用邻接矩阵的时间复杂度为O(n^{2}),邻接表为O(n\log e)
  • 克鲁斯卡尔算法使用并查集实现,适用于边稀疏图,时间复杂度为eO(\log e)

记住两种算法的模板

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容