A province investigates urban traffic conditions and obtains statistical tables of existing urban roads, which list the towns where each road is directly connected. The goal of the provincial government's "unblocked project" is to enable traffic to be achieved between any two towns in the province (but not necessarily directly connected to each other, as long as they can be reached indirectly through the road). How many roads must be built at least.
Chinese problem, not much description. Practice: And check set or BFS, DFS
# include <cstdio> # include <cstring> # include <iostream> using namespace std;
const int MAXN = 1010;
int CITY[MAXN];
int find_root (int x) {return (x = = City[x])? X:city[x] = Find_root (City[x]);}
void Union (int x, int y) {city[x] = find_root (x);
City[y] = Find_root (y);
if (city[x]! = City[y]) {city[city[x]] = city[y];
}} int main () {//freopen ("In.txt", "R", stdin);
int n, m;
while (scanf ("%d", & N), N) {memset (city, 0, sizeof);
for (int i = 1; I <= n; i + +) {City[i] = i;
} scanf ("%d", & M);
while (M--) {int w1, W2;
scanf ("%d%d", & W1, & W2);
Union (W1, W2);
} int more_way = 0;
for (int i = 1; I <= n; i + +) {if (city[i] = = i) More_way + +;
} cout << more_way-1 << Endl;
} return 0;
}