1013 Battle Over Cities (25point(s)) 需要二刷 *注意关于大数据样本下用scanf的问题/并查集

基本思想:

难倒是不难,利用并查集进行查询,但是卡在了最后一个测试点,存在TL的问题,最后发现是cin和scanf效率的问题;

 

关键点:

以后输入输出在OJ方面用scanf;

char a[]转string直接用.c_str()和s=a即可;

 

#include
#include
#include
#include 
#include
#include
#include
#include
#include
#include
using namespace std;

const int maxn = 1010;
vector>matrix;
vectorfather;
vectorflag;

int findfather(int n) {
	int temp = n;
	while (n != father[n]) {
		n = father[n];
	}
	while(temp!=father[temp]){
		int z = temp;
		temp = father[temp];
		father[z] = n;
	}
	return n;
}

void union_father(int a, int b) {
	int aa = findfather(a);
	int bb = findfather(b);
	if (aa != bb) {
		father[aa] = bb;
	}
}

void init(int n) {
	father.resize(n + 1);
	flag.resize(n + 1);
	fill(flag.begin(),flag.end(), true);
	for (int i = 0; i < father.size(); i++) {
		father[i] = i;
	}
}

int cnt(int n) {
	int c=0;
	for (int i = 1; i <= n; i++) {
		if (father[i] == i) {
			c++;
		}
	}
	return c-1;
}



int main() {
	//fill(matrix, matrix + maxn * maxn, 0);
	int n, m, k;
	int a, b;
	scanf("%d %d %d", &n, &m, &k);
	matrix.resize(n + 1);
	for (int i = 0; i < m; i++) {
		scanf("%d %d", &a, &b);
		matrix[a].push_back(b);
		matrix[b].push_back(a);
	}
	for (int i = 0; i < k; i++) {
		cin >> a;
		init(n);
		flag[a] = false;
		//进行边的枚举;
		for (int i = 1; i <= n; i++) {
			for (int j = 0; j < matrix[i].size(); j++) {
				if (flag[i] && flag[matrix[i][j]]) {
					//统计未排除的边;
					union_father(i, matrix[i][j]);
				}
			}
		}
		printf("%d\n", cnt(n) - 1);
		//flag[a] = true;
	}
	return 0;
}

  

你可能感兴趣的:(1013 Battle Over Cities (25point(s)) 需要二刷 *注意关于大数据样本下用scanf的问题/并查集)