这个题出的有一点问题,数据量有点大,但是空间给的有点少了,Java好像过不去,只能用Cpp写,是一个最短路的板子。
直接克鲁斯卡尔,有点忘了,基于并查集思想。
cpp AC code
#include <bits/stdc++.h>
using namespace std;
const int N = 2310, M = 400010, INF = 0x3f3f3f3f;
int n, m;
int p[N];
struct Edge
{
int a, b, w;
bool operator< (const Edge &W)const
{
return w < W.w;
}
}edges[M];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int kruskal()
{
sort(edges, edges + m);
for (int i = 1; i <= n; i ++ ) p[i] = i;
int res = 0, cnt = 0;
for (int i = 0; i < m; i ++ )
{
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
a = find(a), b = find(b);
if (a != b)
{
p[a] = b;
res += w;
cnt ++ ;
}
}
if (cnt < n - 1) return INF;
return res;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i ++ )
{
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
edges[i] = {a, b, w};
}
int t = kruskal();
if (t == INF) puts("impossible");
else cout << t;
return 0;
}
Java Kruskal Template
基于并查集
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static class InputReader {
public BufferedReader Reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
Reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(Reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int N = 100001, M = 200002, n, m;
static int p[] = new int[N];
static Edge[] e = new Edge[M];
public static void main(String[] args) throws IOException {
n = in.nextInt();
m = in.nextInt();
for (int i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
e[i] = new Edge(a, b, c);
}
Arrays.sort(e, 0, m);
for (int i = 0; i < n; i++)
p[i] = i;
int res = 0;
int cnt = 0;
for (int i = 0; i < m; i++) {
int a = e[i].a;
int b = e[i].b;
int c = e[i].c;
if (!judge(a, b)) {
p[find(a)] = find(b);
res += c;
cnt++;
}
}
if (cnt < n - 1)
out.println("impossible");
else
out.println(res);
out.flush();
}
public static boolean judge(int a, int b) {
return find(a) == find(b);
}
public static int find(int x) {
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
}
class Edge implements Comparable<Edge> {
int a, b, c;
public Edge(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(Edge edge) {
return this.c - edge.c;
}
}