1013. Battle Over Cities (25)

1.采用邻接矩阵才不会超内存,一开始采用edge的结构体存储,结果出现段错误(内存爆满)

2.采用并查集的方法,统计时,遇到破坏的城市则不处理,否则进行合并

3.最终检查并查集的集合数,集合数-2就是结果(集合数m减去破坏的城市,即m-1,令n=m-1,剩下的集合数n,需要采用n-1条边才能连接起来)


//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
//#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;
struct edgeNode{
	int a, b;
	edgeNode() :a(0), b(0){};
};
int find(int k, vector<int>&r)
{
	if (r[k] == k)
		return r[k];
	else
	{
		r[k] = find(r[k], r);
		return r[k];
	}
}
int main(void) {

	int n, m, k;
	cin >> n >> m >> k;
	n++;//城市从1开始,方便操作
	vector<vector<bool>> w(n, vector<bool>(n, false));//使用邻接矩阵存储,避免超时超内存,之前使用edge存储,结果段错误(超内存了)
	for (int i = 0; i < m; i++)
	{//输入边
		int a, b;
		cin >> a >> b;
		w[a][b] = true;
		w[b][a] = true;
	}
	for (int i = 0; i < k; i++)
	{
		int city;
		cin >> city;
		static vector<int> r(n, 0);
		for (int i = 0; i < n; i++)
			r[i] = i;
		//r[city] = 10000;
		for (int i = 1; i < n; i++)
		{
			if (i == city) continue;
			for (int j = i; j < n; j++)
			{
				if (j == city) continue;
				if (w[i][j])
					r[find(j, r)] = find(i, r);//否则合并两个城市
			}
		}
		int sum = -2;
		for (int i = 1; i < n; i++)
			if (r[i] == i) sum++;
		cout << sum << endl;
	}


	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值