注意一点:数组初始化
int array1[10] = {0}:输出每个元素,值都是0
int array2[10] = {-1}:输出每个元素,array2[0]为-1,其他都是0!
天真的我之前以为这样可以让数组的每一个元素都初始化为同一个值,但是不行!
bool array3[10] = {false}:每个元素值都为false
bool array4[10] = {true}:array4[0]为true,其他都是false
这可能涉及默认值什么的...之前做的一些题也犯了同样的错误,不过可能碰巧都是默认值
总之一定要注意!
#include <iostream>
#define MAXNUM 10000
using namespace std;
// 并查集
// 路径压缩, 可让id到根节点路径上的所有点都直接指向根节点
// 事实上是伪递归(why?), 伪递归不会因为压入结点过多让堆栈爆掉, 因为伪递归很容易转换成循环, 而编译器正会这么做
int find( int gragh[], int id ) { // id是目标点的数组下标, 目标点编号为id+1
if( gragh[id] < 0 ) // 找到集合的根
return id;
else // 先找到根, 把根变成id的父节点, 再返回根
return gragh[id] = find( gragh, gragh[id] );
}
// 按秩归并: 比树高 或 比规模(结点数)
// 这里采用比规模, 因为有路径压缩
void Union( int gragh[], int root1, int root2 ) {
// 默认根节点不同
if( gragh[root2] < gragh[root1] ) { // 若root2规模更大(负数比较)
gragh[root2] += gragh[root1]; // 大树(root2)更新规模
gragh[root1] = root2; // 小树(root1)贴大树(root2)
}
else { // root1规模更大
gragh[root1] += gragh[root2];
gragh[root2] = root1;
}
}
void inputCon( int gragh[] ) {
int u, v, root1, root2;
cin >> u >> v;
root1 = find( gragh, u-1 ); // 下标是编号-1
root2 = find( gragh, v-1 );
if( root1 != root2 ) // 根节点不同则并集
Union( gragh, root1, root2 );
}
void checkCon( int gragh[] ) {
int u, v, root1, root2;
cin >> u >> v;
root1 = find( gragh, u-1 ); // 下标是编号-1
root2 = find( gragh, v-1 );
if( root1 == root2 ) cout << "yes" << endl;
else cout << "no" << endl;
}
void checkNetwork( int gragh[], int N ) {
int count = 0;
for( int i = 0; i < N; i++ )
if( gragh[i] < 0 ) // 计算根节点个数
count++;
if( count == 1 ) cout << "The network is connected." << endl;
else cout << "There are " << count <<" components." << endl;
}
int main() {
int gragh[MAXNUM]; // 注意从1开始编号
int N; // 电脑总数
char op;
cin >> N;
for( int i = 0; i < N; i++ ) // 全部初始化为-1: -表示自己是自己的根节点, 1表示自己这个集合的点数
gragh[i] = -1;
do {
cin >> op;
switch( op ) {
case 'I': inputCon(gragh); break; // 建立连接
case 'C': checkCon(gragh); break; // 有无连接
case 'S': checkNetwork(gragh, N); break; // 是否为连通图
}
} while( op != 'S' );
return 0;
}