• HDU 5253 连接的管道(prim+优先队列)


    连接的管道



    Problem Description
    老 Jack 有一片农田,以往几年都是靠天吃饭的。但是今年老天格外的不开眼,大旱。所以老 Jack 决定用管道将他的所有相邻的农田全部都串联起来,这样他就可以从远处引水过来进行灌溉了。当老 Jack 买完所有铺设在每块农田内部的管道的时候,老 Jack 遇到了新的难题,因为每一块农田的地势高度都不同,所以要想将两块农田的管道链接,老 Jack 就需要额外再购进跟这两块农田高度差相等长度的管道。

    现在给出老 Jack农田的数据,你需要告诉老 Jack 在保证所有农田全部可连通灌溉的情况下,最少还需要再购进多长的管道。另外,每块农田都是方形等大的,一块农田只能跟它上下左右四块相邻的农田相连通。
     
    Input
    第一行输入一个数字T
    代表输入的样例组数

    输入包含若干组测试数据,处理到文件结束。每组测试数据占若干行,第一行两个正整数N,M,N                     ,M(1N,M
     
    代表老 Jack 有N行*M列个农田。接下来 N 行,每行 M 个数字,代表每块农田的高度,农田的高度不会超过100。数字之间用空格分隔。
     
    Output
    对于每组测试数据输出两行:

    第一行输出:"Case #i:"。i代表第i组测试数据。

    第二行输出 1 个正整数,代表老 Jack 额外最少购进管道的长度。
     
    Sample Input
    2
    4 3
    9 12 4
    7 8 56
    32 32 43
    21 12 12
    2 3
    34 56 56
    12 23 4
     
     
    Sample Output
    Case #1: 82
    Case #2: 74
     1 #include<cstdio>
     2 #include<queue>
     3 #include<algorithm>
     4 #include<cstring>
     5 #include<cmath>
     6 using namespace std;
     7 
     8 int G[1005][1005];
     9 int vis[1005][1005];
    10 int d[4][2]={1,0,0,1,-1,0,0,-1};
    11 int m,n;
    12 const int inf=0x3f3f3f3f;
    13 
    14 int cal(int x1,int y1,int x2,int y2)
    15 {
    16     return abs(G[x1][y1]-G[x2][y2]);
    17 };
    18 
    19 struct lowercost
    20 {
    21     int x,y;
    22     int cost;
    23     bool operator < (const lowercost &temp)const
    24     {
    25         return cost>temp.cost;
    26     }
    27 };
    28 
    29 void init()
    30 {
    31     memset(vis,0,sizeof(vis));
    32 }
    33 
    34 int prim()
    35 {
    36     priority_queue<lowercost>q;
    37     lowercost t1,t2;
    38     int sum=0,i,cnt;
    39     t1.x=t1.y=t1.cost=0;
    40     q.push(t1);
    41     cnt=0;
    42     while(!q.empty())
    43     {
    44         t1=q.top();
    45         q.pop();
    46         if(vis[t1.x][t1.y])
    47         continue;
    48         vis[t1.x][t1.y]=1;
    49         sum+=t1.cost;
    50         for(i=0;i<4;i++)
    51         {
    52             t2.x=t1.x+d[i][0];
    53             t2.y=t1.y+d[i][1];
    54             t2.cost=cal(t1.x,t1.y,t2.x,t2.y);
    55             if(t2.x>=0&&t2.x<m&&t2.y>=0&&t2.y<n&&!vis[t2.x][t2.y])
    56             q.push(t2);
    57         }
    58     }
    59     return sum;
    60 }
    61 
    62 int main()
    63 {
    64     int t,i;
    65     scanf("%d",&t);
    66     for(i=1;i<=t;i++)
    67     {
    68         init();
    69         scanf("%d%d",&m,&n);
    70         for(int i=0;i<m;i++)
    71         for(int j=0;j<n;j++)
    72         scanf("%d",&G[i][j]);
    73         int ans=prim();
    74         printf("Case #%d:
    ",i);
    75         printf("%d
    ",ans);
    76     }
    77     return 0;
    78 }
  • 相关阅读:
    jsp第六周作业
    jsp第三周作业
    JSP第二次作业
    软件测试课堂练习(3.4)
    10.21
    10.7
    9.30
    9.23
    第四次作业
    第七周作业
  • 原文地址:https://www.cnblogs.com/homura/p/4735737.html
Copyright © 2020-2023  润新知