畅通工程(浙大2005上机)
Problem Description
某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最少还需要建设的道路数目。
Sample Input
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Sample Output
1
0
2
998
遍历求出连通子图的个数,然后就求出要加的道路条数了,我总能想出最笨最慢的方法,怎么这么笨呢?
#include <iostream>
#include <fstream>
#include <cstring>
#include <stack>
using namespace std;
int roads[1000][1000];
int visited[1000];
int main(void)
{
int m,n,i,j;
ifstream cin("hello.txt");
while(true)
{
int a,b;
cin >>n;
if (n == 0)
break;
cin >> m;
if (m == 0)
{
cout << n-1 << endl;
continue;
}
// 清零
memset(visited, 0, sizeof(int) * (n));
for (i = 0; i < n; i++)
memset(roads[i], 0, sizeof(roads[i]));
// 读入道路
for (i = 0; i < m; i++)
{
cin >> a >> b;
roads[a-1][b-1] = 1;
roads[b-1][a-1] = 1;
}
int start;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (roads[i][j] != 0)
{
start = i;
goto out;
}
}
}
out:
int count = 0;
for (j = 0; j < n; j++)
{
if (!visited[j])
count++;
else
continue;
stack<int> st;
visited[j] = 1;
st.push(j);
while (!st.empty())
{
int v = st.top();
st.pop();
for (i = 0; i < n; i++)
{
if (roads[v][i] && !visited[i])
{
visited[i] = 1;
st.push(i);
}
}
}
}
cout << count-1 << endl;
}
return 0;
}
下面一个使用并查集实现的,并查集真的很强大,要多学习啊:
#include <iostream>
#include <fstream>
using namespace std;
int father[1000];
int rank[1000];
void makeSet(int n)
{
for (int i = 0; i < n; i++)
{
father[i] = i;
rank[i] = 1;
}
}
int findSet(int x)
{
if (x != father[x])
{
father[x] = findSet(father[x]);
}
return father[x];
}
void unionSet(int fx, int fy)
{
if(rank[fx] < rank[fy])
{
father[fx] = fy;
rank[fy] += rank[fx];
}
else
{
father[fy] = fx;
rank[fx] += rank[fy];
}
}
int main(void)
{
int n,m;
//ifstream cin("hello.txt");
while(cin >> n && n !=0)
{
makeSet(n);
cin >> m;
int a,b,i,fx,fy;
int count = n-1; //使n的定点连通的最少边数为n-1
for (i = 0; i < m; i++)
{
cin >> a >> b;
fx = findSet(a-1); //因为我的下标是从0开始的所以减了1
fy = findSet(b-1);
if (fx != fy) //如果a,b的祖先不一样,说明a或b不在已建立起的连通图中
{ //及a和b间的道路是n-1条中必须的一条
unionSet(fx,fy);
count--;
}
}
cout << count << endl;
}
return 0;
}

浙公网安备 33010602011771号