修路
Time Limit: 1000ms
Memory Limit: 65536KB
64-bit integer IO format:
%lld Java class name:
Main
Prev
Submit Status Statistics Discuss
Next
Type:
None Graph Theory 2-SAT Articulation/Bridge/Biconnected Component Cycles/Topological Sorting/Strongly Connected Component Shortest Path Bellman Ford Dijkstra/Floyd Warshall Euler Trail/Circuit Heavy-Light Decomposition Minimum Spanning Tree Stable Marriage Problem Trees Directed Minimum Spanning Tree Flow/Matching Graph Matching Bipartite Matching Hopcroft–Karp Bipartite Matching Weighted Bipartite Matching/Hungarian Algorithm Flow Max Flow/Min Cut Min Cost Max Flow DFS-like Backtracking with Pruning/Branch and Bound Basic Recursion IDA* Search Parsing/Grammar Breadth First Search/Depth First Search Advanced Search Techniques Binary Search/Bisection Ternary Search Geometry Basic Geometry Computational Geometry Convex Hull Pick's Theorem Game Theory Green Hackenbush/Colon Principle/Fusion Principle Nim Sprague-Grundy Number Matrix Gaussian Elimination Matrix Exponentiation Data Structures Basic Data Structures Binary Indexed Tree Binary Search Tree Hashing Orthogonal Range Search Range Minimum Query/Lowest Common Ancestor Segment Tree/Interval Tree Trie Tree Sorting Disjoint Set String Aho Corasick Knuth-Morris-Pratt Suffix Array/Suffix Tree Math Basic Math Big Integer Arithmetic Number Theory Chinese Remainder Theorem Extended Euclid Inclusion/Exclusion Modular Arithmetic Combinatorics Group Theory/Burnside's lemma Counting Probability/Expected Value Others Tricky Hardest Unusual Brute Force Implementation Constructive Algorithms Two Pointer Bitmask Beginner Discrete Logarithm/Shank's Baby-step Giant-step Algorithm Greedy Divide and Conquer Dynamic Programming Tag it!
在某个景区内有n个景点,它们之间有m条路相连。然而,这m条路可能是不足够的,因为无法把这n个景点都连通起来。
例如当m<n-1的时候,就必定有部分景点被孤立。
所以,现在政府想修建道路,想把这些景点都连通起来。问题是,在现在的基础上,最少要再修建多少条道路呢?
Input
第一行是n,m (1<=n<=1e5,1<=m<=1e6)
接下来就是m行,每行两个1 ~ n范围内的数,表示编号为这两个数的景点之间有一道路相连
Output
Sample Input
5 2
1 2
3 4
Sample Output
2
Source
第八届北京师范大学程序设计竞赛热身赛第四场
思路:就是去寻找连通分量的个数cnt,最少修建的道路个数即为cnt-1(犯了两超傻逼错误╮(╯_╰)╭)
AC代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 100005;
int pa[maxn], vis[maxn];
int find(int x) {
return pa[x] != x ? pa[x] = find(pa[x]) : x;
}
int main() {
int n, m;
while(scanf("%d %d", &n, &m) != EOF) {
for(int i = 0; i <= n; i++) pa[i] = i;
memset(vis, 0, sizeof(vis));
while(m--) {
int a, b;
scanf("%d %d", &a, &b);
a = find(a), b = find(b);
if(a != b) pa[a] = b;
}
int cnt = 0;
for(int i = 1; i <= n; i++) {
int tmp = find(i);
if(!vis[tmp]) {
vis[tmp] = 1;
cnt++;
}
}
printf("%d\n", cnt-1);
}
return 0;
}