其他分享
首页 > 其他分享> > 洛谷 P3073 [USACO13FEB]拖拉机Tractor

洛谷 P3073 [USACO13FEB]拖拉机Tractor

作者:互联网

洛谷 P3073 [USACO13FEB]拖拉机Tractor

Description

Input

Output

Sample Input

5 
0 0 0 3 3 
0 0 0 0 3 
0 9 9 3 3 
9 9 9 3 3 
9 9 9 9 3 

Sample Output

3 

题解:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define N 505
#define M (500 * 500 * 2)
using namespace std;

struct E {int u, v, w;} e[M];
int n, tot, cnt, ans;
int fat[N * N], size[N * N];
int a[N][N];

int cal(int x, int y) {return (x - 1) * n + y;}
bool cmp(E x, E y) {return x.w < y.w;}

int getFat(int x)
{
    if(x == fat[x]) return x;
    return fat[x] = getFat(fat[x]);
}

int main()
{
    cin >> n, tot = n * n / 2;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            scanf("%d", &a[i][j]);
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
        {
            int x = i, y = j + 1;
            if(x >= 1 && x <= n && y >= 1 && y <= n)
            {
                e[++cnt].u = cal(i, j);
                e[cnt].v = cal(x, y);
                e[cnt].w = abs(a[i][j] - a[x][y]);
            }
            x = i + 1, y = j;
            if(x >= 1 && x <= n && y >= 1 && y <= n)
            {
                e[++cnt].u = cal(i, j);
                e[cnt].v = cal(x, y);
                e[cnt].w = abs(a[i][j] - a[x][y]);
            }
        }
    for(int i = 1; i <= n * n; i++)
        fat[i] = i, size[i] = 1;
    sort(e + 1, e + 1 + cnt, cmp);
    for(int i = 1; i <= cnt; i++)
    {
        int fx = getFat(e[i].u), fy = getFat(e[i].v);
        if(fx == fy) continue;
        if(size[fx] > size[fy]) swap(fx, fy);
        size[fy] += size[fx], fat[fx] = fy;
        if(size[fy] >= tot) {cout << e[i].w; break;}
    }
    return 0;
}

标签:P3073,洛谷,格子,int,fy,fat,USACO13FEB,拖拉机,size
来源: https://www.cnblogs.com/BigYellowDog/p/11505418.html