1013 Battle Over Cities

部分正确,只适用于全部联通的图:

#include<iostream>
#include<vector>
using namespace std;
int main() {
	int N, M, K,i,a,b,w,e,j=0,r,need;
    cin >> N >> M >> K;
	vector<int>u, v,ne,first(N+1, -1);
	if (N == 1) {
		cout << "0" << endl;
		return 0;
	}
		for (i = 1; i <= M; i++) {
		cin >> a >> b;
		u.push_back(a);
		v.push_back(b);
		ne.push_back(first[a]);
		first[a] = j;
		j++;
		u.push_back(b);
		v.push_back(a);
		ne.push_back(first[b]);
		first[b] = j;
		j++;
    }
	for (i = 1; i <= K; i++) {
		int r;
		cin >> w;
		r = 0;
		for (e = first[w]; e != -1; e=ne[e]) {
			r++;
		}
		need = N - 2 - j / 2 + r;
		if (need >= 0)
			cout << need << endl;
		else
			cout << "0"<<endl;
	}
	return 0;
}

正确解法(BFS+邻接表):

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<int>u, v, ne, first;
vector<bool>book;
void bfs(int i) {
	int j;
	queue<int>city;
	city.push(i);
	while (!city.empty()) {
		for (j = first[city.front()]; j != -1; j = ne[j]) {
			if (!book[v[j]]) {
				book[v[j]] = true;
	            city.push(v[j]);
			}
		}
		city.pop();
	}
	return;
}
int main() {
	int N,M,K,i,a,b,w,j=0,r;
    cin >> N >> M >> K;
	first=vector<int>(N+1, -1);
    for (i = 1; i <= M; i++) {
		cin >> a >> b;
		u.push_back(a);
		v.push_back(b);
		ne.push_back(first[a]);
		first[a] = j;
		j++;
		u.push_back(b);
		v.push_back(a);
		ne.push_back(first[b]);
		first[b] = j;
		j++;
    }
	for (i = 1; i <= K; i++) {
	    book=vector<bool>(N + 1, false);
		cin >> w;
		r = 0;
		book[w] = true;
		for (j = 1; j <= N; j++) {
			if (!book[j]) {
				book[j] = true;
				bfs(j);
				r++;
			}
		}
		if (r > 0)
			cout << r - 1 << endl;
		else
			cout << "0" << endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值