【站外题】【闻灌多】【ygg me plz】【0pts】【Prim】
  • 板块灌水区
  • 楼主_VirtualPoint_
  • 当前回复5
  • 已保存回复5
  • 发布时间2024/8/6 07:50
  • 上次更新2024/8/6 09:47:10
查看原帖
【站外题】【闻灌多】【ygg me plz】【0pts】【Prim】
794507
_VirtualPoint_楼主2024/8/6 07:50

此题最小生成树也,但撇蒟挂于其Prim。

此为撇蒟之代码,由另一题改编而来,类型可能稍加不对,恕罪:

#include <iostream>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <algorithm>
using namespace std;

int n, m;
int a, b;

int vis[1005];
long long pth[1005];

long long w[1005][1005];

struct point {
	long long x, y, z;
	long long id;
} pt[1005];

bool cmpx(point a, point b) {
	return a.x < b.x;
}

bool cmpy(point a, point b) {
	return a.y < b.y;
}

bool cmpz(point a, point b) {
	return a.z < b.z;
}

long long prim() {
	memset(vis, 0, sizeof(vis));
	
	for (int i = 0; i <= 1004; i++) {
		pth[i] = 1e12;
	}
	
	pth[1] = 0;
	
	long long res=0;
	
	for (int i = 0; i < n; i++) {
		int u = -1;
		
		for (int v = 1; v <= n; v++) {
			if (!vis[v] && (u == -1 || pth[v] < pth[u])) {
				u = v;
			}
		}
		
//		if (pth[u] == pth[1004]) {
//			return -1;
//		}
		
		vis[u] = true;
		res += pth[u];
		
		for (int v = 1; v <= n; v++) {
			pth[v] = min(pth[v], w[u][v]);
		}
		
//		for (int i = 1; i <= n; i++) {
//			cout << pth[i] << " ";
//		}
//		cout <<endl;
	}
	
	return res;
}

int main() {
	cin >> n;
	
	memset(w, 127, sizeof(w));
	
	for (long long i = 1; i <= n; i++) {
		cin >> pt[i].x >> pt[i].y >> pt[i].z;
		
		pt[i].id = i;
	}
	
	sort(pt+1, pt+n+1, cmpx);
	
    for (long long i = 1; i < n; i++) {
    	if (w[pt[i].id][pt[i+1].id] == w[1004][1004]) {
    		w[pt[i].id][pt[i+1].id] = abs(pt[i+1].x - pt[i].x);
		}
        w[pt[i].id][pt[i+1].id] = min(w[pt[i].id][pt[i+1].id], abs(pt[i+1].x - pt[i].x));
    }
    
//    for (int i = 1; i <= n; i++) {
//		for (int j = 1; j <= n; j++) {
//			cout <<w[i][j] << " ";
//		}
//		cout <<endl;
//	}
//	cout << "----------------------" << endl;
	
    sort(pt+1, pt+n+1, cmpy);
    
    for (long long i = 1; i < n; i++) {
    	if (w[pt[i].id][pt[i+1].id] == w[1004][1004]) {
    		w[pt[i].id][pt[i+1].id] = abs(pt[i+1].y - pt[i].y);
		}
        w[pt[i].id][pt[i+1].id] = min(w[pt[i].id][pt[i+1].id], abs(pt[i+1].y - pt[i].y));
	}
	
//	for (int i = 1; i <= n; i++) {
//		for (int j = 1; j <= n; j++) {
//			cout << w[i][j] << " ";
//		}
//		cout <<endl;
//	}
//	cout << "----------------------" << endl;
    
    sort(pt+1, pt+n+1, cmpz);
    
    for (long long i = 1; i < n; i++) {
    	if (w[pt[i].id][pt[i+1].id] == w[1004][1004]) {
    		w[pt[i].id][pt[i+1].id] = abs(pt[i+1].z - pt[i].z);
		}
        w[pt[i].id][pt[i+1].id] = min(w[pt[i].id][pt[i+1].id], abs(pt[i+1].z - pt[i].z));
    }
	
//	for (int i = 1; i <= n; i++) {
//		for (int j = 1; j <= n; j++) {
//			cout <<w[i][j] << " ";
//		}
//		cout <<endl;
//	}
//	cout << "----------------------" << endl;
	
	cout << fixed << setprecision(0) << prim() << endl;
	return 0;
}

可否请众位巨佬供不对之处讲解,或提出Prim做法?

玄关、加团

2024/8/6 07:50
加载中...