intprime() { memset(dist, 0x3f, sizeof dist); int ans = 0; // 用于存储最小生成树中所有边权之和 for (int i = 0; i < n; i ++) { int t = -1; for (int j = 1; j <= n; j ++) if (!st[j] && (t == -1 || dist[t] > dist[j])) t = j; // 取出集合外距离集合最近的点 if (i && dist[t] == INF) return INF; // 如果不是第一个点并且距离为正无穷,说明该图不连通 // 则没有最小生成树,判无解 if (i) ans += dist[t]; // 如果不是第一个点,则将该点边权加入最小生成树 for (int j = 1; j <= n; j ++) dist[j] = min(dist[j], g[t][j]); // 使用该点进行更新 st[t] = true; // 将该点加入集合 } return ans; }
intmain() { cin >> n >> m; memset(g, 0x3f, sizeof g); while (m --) { int u, v, w; cin >> u >> v >> w; g[u][v] = g[v][u] = min(g[v][u], w); } int t = prime(); if (t == INF) puts("impossible"); else cout << t << endl; }
structnode { int a, b, w; booloperator < (const node &t) const { return w < t.w; } }edge[N];
int p[N]; // 并查集 father 数组 intfind(int x) { if (p[x] != x) p[x] = find(p[x]); return p[x]; }
int n, m;
voidkruskal() { sort(edge, edge + m); for (int i = 1; i <= n; i ++) p[i] = i; // 初始化并查集 int res = 0, cnt = 0; // res 存储最小生成树中边权之和 // cnt 存储最小生成树中边数 for (int i = 0; i < m; i ++) { int a = edge[i].a, b = edge[i].b, w = edge[i].w;
a = find(a), b = find(b); if (a != b) { p[a] = b; res += w; cnt ++; } } if (cnt < n - 1) puts("impossible"); else cout << res << endl; }
intmain() { cin >> n >> m; for (int i = 0; i < m ;i ++) { int a, b, w; cin >> a >> b >> w; edge[i] = {a, b, w}; } kruskal(); }
booldfs(int u, int c) // point and color { color[u] = c; for (int i = h[u]; i != -1; i = edge[i].nxt) { int t = edge[i].to; if (!color[t] && !dfs(t, 3 - c)) returnfalse; elseif (color[t] == c) returnfalse; } returntrue; }
intmain() { memset(h, -1, sizeof h); // init cin >> n >> m; for (int i = 0; i < m; i ++) { int a, b; cin >> a >> b; add(a, b), add(b, a); } // input bool judge = true; for (int i = 1; i <= n; i ++) if (!color[i] && !dfs(i, 1)) { judge = false; break; } if (judge) puts("Yes"); elseputs("No"); return0; }
int h[N], idx; structnode { int val, nxt; }edge[M];
int match[N]; // 存储右侧的对应关系 bool st[N]; // 存储是否考虑过该点
voidadd(int a, int b) { edge[++ idx].val = b; edge[idx].nxt = h[a]; h[a] = idx; }
boolfind(int x) { for (int i = h[x]; i != -1; i = edge[i].nxt) { int t = edge[i].val; if (!st[t]) { st[t] = true; if (match[t] == 0 || find(match[t])) // 右侧点可用 { match[t] = x; returntrue; } } } returnfalse; }
intmain() { memset(h, -1, sizeof h); // init cin >> n1 >> n2 >> m; while (m --) { int a, b; cin >> a >> b; add(a, b); } // input int res = 0; // 当前匹配数量 for (int i = 1; i <= n1; i ++) { memset(st, false, sizeof st); if (find(i)) res ++; } cout << res << endl; return0; }