- 题目描述:
-
某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
- 输入:
-
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。- 输出:
-
对每个测试用例,在1行里输出最少还需要建设的道路数目。
- 样例输入:
-
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
- 样例输出:
-
1 0 2 998
典型的并查集问题#include#include using namespace std; #define MAX 1005 int N,M; int a,b; int field[MAX]; int ans; int find(int x){ if(field[x]==0)return x; field[x]=find(field[x]); return field[x]; } void merge(int x,int y){ int f1=find(x); int f2=find(y); if(f1!=f2){ field[f2]=f1; ans--; } } int main() { //freopen("C:\\in.txt","r",stdin); while(cin>>N&&N) { cin>>M; memset(field,0,sizeof(field)); ans=N; while(M--) { cin>>a>>b; merge(a,b);//将a b合并 } cout<
- <script type="text/java script">BAIDU_CLB_fillSlot("771048");
- 点击复制链接 与好友分享! 回本站首页 <script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
<script type="text/java script" id="bdshare_js" data="type=tools&uid=12732"> <script type="text/java script" id="bdshell_js"> <script type="text/java script"> var bds_config = {'snsKey':{'tsina':'2386826374','tqq':'5e544a8fdea646c5a5f3967871346eb8'}}; document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js cdnversion=" + Math.ceil(new Date()/3600000) - 您对本文章有什么意见或着疑问吗?请到 论坛讨论您的关注和建议是我们前行的参考和动力
- 上一篇: C++11 std - auto
- 下一篇: UVA - 11991 Easy Problem from Rujia Liu
- 相关文章
- <script type="text/java script">BAIDU_CLB_fillSlot("182716");
- <script type="text/java script">BAIDU_CLB_fillSlot("517916");
- 图文推荐
<iframe src="http://www.2cto.com/uapi.php tid=278948&catid=339&title=vsW2yKO6zOLEvzEwMTKjurOpzai5pLPM&forward=http://www.2cto.com/kf/201402/278948.html" width="100%" height="100%" id="comment_iframe" name="comment_iframe" frameborder="0" scrolling="no">- <script type="text/java script">BAIDU_CLB_fillSlot("771057");



