我写出来了过不了
2024-02-09 11:13:40
发布于:江苏
3阅读
0回复
0点赞
以下为正文:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
const int MOD = 1e9 + 7;
struct Edge {
int u, v, weight;
bool operator<(const Edge &other) const {
return weight < other.weight;
}
};
struct UnionFind {
vector<int> parent;
UnionFind(int n) : parent(n) {
iota(parent.begin(), parent.end(), 0);
}
int find(int x) {
if (x != parent[x])
parent[x] = find(parent[x]);
return parent[x];
}
void unite(int x, int y) {
parent[find(x)] = find(y);
}
};
int main() {
int N, K;
cin >> N >> K;
vector<Edge> edges;
int edgeCount = (N - 1) * K + (K - 1) * N;
edges.reserve(edgeCount);
// Read horizontal edges
for (int i = 0; i < N; ++i) {
for (int j = 0; j < K - 1; ++j) {
int weight;
cin >> weight;
edges.push_back({i * K + j, i * K + j + 1, weight});
}
}
// Read vertical edges
for (int j = 0; j < K; ++j) {
for (int i = 0; i < N - 1; ++i) {
int weight;
cin >> weight;
edges.push_back({i * K + j, (i + 1) * K + j, weight});
}
}
// Sort edges by weight
sort(edges.begin(), edges.end());
UnionFind uf(N * K);
vector<int> weightCounts(1e9 + 1, 0);
int totalWeight = 0;
int numEdges = 0;
// Kruskal's algorithm
for (const Edge &e : edges) {
if (uf.find(e.u) != uf.find(e.v)) {
uf.unite(e.u, e.v);
totalWeight += e.weight;
weightCounts[e.weight]++;
numEdges++;
if (numEdges == N * K - 1) break; // Found a MST
}
}
// Count number of MSTs
long long result = 1;
for (int i = 0; i <= 1e9; ++i) {
if (weightCounts[i] > 0) {
result *= weightCounts[i];
result %= MOD;
}
}
cout << result << endl;
return 0;
}
好像有点超时了
最后是46.72MB
这里空空如也
有帮助,赞一个