为什么chatGPT的答案都没过
2024-02-09 11:15:18
发布于:江苏
12阅读
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;
}
这里空空如也
有帮助,赞一个