cjweffort

博客园 首页 联系 订阅 管理

考察并查集,注意:边数可能很大,利用动态数组自动管理。

// 1013. Battle Over Cities.cpp: 主项目文件。

#include "stdafx.h"
#include <cstdio>
#include <vector>
using namespace std;

const int N=1003;
int fa[N];
typedef struct EDGE{
	int from,to;
}EDGE;
vector<EDGE> road;
int n,m,enemy;

void init(){
	for(int i=0;i<N;i++)
		fa[i]=-1;
}

int findSet(int x){
	if(fa[x]==-1)
		return x;
	int ret=findSet(fa[x]);
	fa[x]=ret;
	return ret;
}

int Union(){
	init();
	int cnt=0;
	for(int i=0;i<m;i++){
		int ff=road[i].from,tt=road[i].to;
		if(ff!=enemy&&tt!=enemy){
			int root1=findSet(ff);
			int root2=findSet(tt);
			if(root1!=root2){
				fa[root1]=root2;
				cnt++;
			}
		}
	}
	return n-2-cnt;
}

int main()
{
	int num;
	scanf("%d%d%d",&n,&m,&num);
	for(int i=0;i<m;i++){
		int from,to;
		scanf("%d%d",&from,&to);
		EDGE edge;
		edge.from=from,edge.to=to;
		road.push_back(edge);
	}
	while(num--){
		scanf("%d",&enemy);
		int res=Union();
		printf("%d\n",res);
	}
    return 0;
}

posted on 2013-03-11 19:25  cjweffort  阅读(157)  评论(0编辑  收藏  举报