Battle Over Cities
简单的并查集应用:
思路
先假设这个点不在图里面,然后构建并查集,算有几个连通分量,算完之后,连通分量数-1就能得到需要修建多少条路。
源码
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int tree[1010];
//ifstream fin("fin.txt");
//streambuf *old = cin.rdbuf(fin.rdbuf());
int N, M, K;
int ans[1010];
struct node
{
int f, r;
};
node edge[1010*1010];
void init()
{
for (int i = 1; i <= N; i++)
{
tree[i] = i;
ans[i] = 0;
}
}
int findroot(int x)
{
int r = x;
while (tree[r] != r)
r = tree[r];
int i = x, j;
while (i != r)
{
j = tree[i];
tree[i] = r;
i = j;
}
return r;
}
void merge(int a, int b)
{
int fx = findroot(a), fy = findroot(b);
if (fx != fy)
{
tree[fy] = fx;
}
}
void solve()
{
int city;
int highway=0;
for (int i = 1; i <= K; i++)
{
cin >> city;
init();
for (int j = 1; j <= M; j++)
{
if (edge[j].f != city &&edge[j].r != city)
{
merge(edge[j].f, edge[j].r);
}
}
for (int j = 1; j <= N; j++)
{
if (j != city)
findroot(j);
}
for (int j = 1; j <= N; j++)
{
if (tree[j]==j&&j!=city)
{
highway++;
}
}
if (!highway)
cout << 0 << endl;
else
cout << highway - 1 << endl;
highway = 0;
}
}
void input()
{
cin >> N >> M >> K;
int c1, c2;
init();
for (int i = 1; i <= M; i++)
{
cin >> c1 >> c2;
edge[i].f = c1;
edge[i].r = c2;
}
if (N)
solve();
else
cout << 0 << endl;
}
int main()
{
input();
return 0;
}