Codeforces Beta Round #25 D題 Roads not only in Berland

來源:互聯網
上載者:User

這題算是資料結構類型的題目了吧,運用並查集可以快速地解決此類問題,從頭往後讀取資料,如果讀取到的兩個點不在同一個集合裡,就將他們合并,否則,這條邊就是多餘的,將多餘的邊放入棧st中。處理完邊之後,線性掃一遍結點數組,找出所有的根結點放入棧done中。

 

之後從st中取出一元素,將done中的兩個元素連起來,然後任意去掉一個元素,留下一個元素,不斷進行,直到棧st空了為止結束迴圈。

 

這個過程主要是運用好棧和並查集。。

第一題和第二題比較簡單,就不在此多說,剩下的題目嘗試寫了下,沒有寫出。

 

My Code:

#include <iostream><br />#include <cstdio><br />#include <cstring><br />#include <cstdlib></p><p>using namespace std;</p><p>const int MAX=1100;<br />struct Node<br />{<br />int x;<br />int y;<br />}st[MAX];<br />int p[MAX],rank[MAX],top=0,done[MAX],dtop=0;<br />int n;</p><p>void init()<br />{<br />for(int i=1;i<=n;i++)<br />{<br />p[i]=i;<br />rank[i]=0;<br />}<br />}</p><p>int Find(int x)<br />{<br />if(p[x]!=x)<br />p[x]=Find(p[x]);</p><p>return p[x];<br />}</p><p>void Link(int x,int y)<br />{<br />if(rank[x]<rank[y])<br />{<br />p[x]=y;<br />}<br />else<br />{<br />p[y]=x;<br />if(rank[x]==rank[y])<br />rank[x]++;<br />}<br />}</p><p>void Union(int x,int y)<br />{<br />Link(Find(x),Find(y));<br />}</p><p>int main()<br />{<br />int x,y;</p><p>scanf("%d",&n);<br />init();<br />for(int i=0;i<n-1;i++)<br />{<br />scanf("%d%d",&x,&y);<br />if(Find(x)!=Find(y))<br />{<br />Union(x,y);<br />}<br />else<br />{<br />st[top].x=x;<br />st[top].y=y;<br />top++;<br />}<br />}</p><p>for(int i=1;i<=n;i++)<br />{<br />if(Find(i)==i)<br />{<br />done[dtop]=i;<br />dtop++;<br />}<br />}</p><p>printf("%d/n",top);<br />while(top)<br />{<br />x=done[dtop-1];<br />y=done[dtop-2];<br />dtop--;<br />top--;<br />printf("%d %d %d %d/n",st[top].x,st[top].y,x,y);<br />}</p><p>return 0;<br />}<br />

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.