Find them, Catch them POJ - 1703(种类并查集)
題意:
在這個(gè)城市里有兩個(gè)黑幫團(tuán)伙,現(xiàn)在給出N個(gè)人,問(wèn)任意兩個(gè)人他們是否在同一個(gè)團(tuán)伙
1.輸入D x y代表x于y不在一個(gè)團(tuán)伙里
2.輸入A x y要輸出x與y是否在同一團(tuán)伙或者不確定他們?cè)谕粋€(gè)團(tuán)伙里
題目:
The police office in Tadu City decides to say ends to the chaos, as launch actions to root up the TWO gangs in the city, Gang Dragon and Gang Snake. However, the police first needs to identify which gang a criminal belongs to. The present question is, given two criminals; do they belong to a same clan? You must give your judgment based on incomplete information. (Since the gangsters are always acting secretly.)
Assume N (N <= 10^5) criminals are currently in Tadu City, numbered from 1 to N. And of course, at least one of them belongs to Gang Dragon, and the same for Gang Snake. You will be given M (M <= 10^5) messages in sequence, which are in the following two kinds:
D [a] [b]
where [a] and [b] are the numbers of two criminals, and they belong to different gangs.
A [a] [b]
where [a] and [b] are the numbers of two criminals. This requires you to decide whether a and b belong to a same gang.
Input
The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. Each test case begins with a line with two integers N and M, followed by M lines each containing one message as described above.
Output
For each message “A [a] [b]” in each case, your program should give the judgment based on the information got before. The answers might be one of “In the same gang.”, “In different gangs.” and “Not sure yet.”
Sample Input
1
5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4
Sample Output
Not sure yet.
In different gangs.
In the same gang.
Sponsor
分析:
這道題用的是種類并查集:并查集把給出的人分成幾個(gè)集合,每個(gè)集合之間的人的關(guān)系不確定,對(duì)同一個(gè)集合保存和本人不為同一隊(duì)的人,本著敵人的敵人便是朋友的原則,用并查集同一集合為同一隊(duì),不同集合為不同隊(duì)。說(shuō)的我自己都繞暈了,23333
1.首先特殊解很重要:當(dāng)N=2時(shí)他們屬于不同的幫派,因?yàn)轭}目有說(shuō)兩個(gè)幫派至少有一個(gè)人。
2.
(1)只要輸入D,就將a,b兩個(gè)合并,歸在同一集合,并將改他們的關(guān)系。
(2)輸入A的時(shí)候判斷a,b是否合并過(guò),如果兩個(gè)不屬于同一個(gè)集合的話就不能確定他們是否在同一個(gè)幫派。
(3)若合并過(guò),即前面已經(jīng)出現(xiàn)過(guò),則有確定關(guān)系即是否在同一幫派。此時(shí)只要判定其dp【】值是否相同,即為一個(gè)隊(duì),為同一幫派,否則不在。
原因:我在把一個(gè)集合合并到另一個(gè)集合時(shí),把x根節(jié)點(diǎn)的dp變成和y根節(jié)點(diǎn)dp相對(duì)的,(每次連兒子保證和父親不是一個(gè)幫派,同時(shí)更新父親)然后在查找的時(shí)候要修改dp值(注意回溯),因?yàn)樯傻臉?shù)每一層和隔層的dp值是相對(duì)的(0和1),因?yàn)閐p的值只能為0和1(只有兩個(gè)幫派),所以類別偏移用位運(yùn)算
(4)若我太啰嗦,可參照 如下AC代碼,有步驟詳解:
總結(jié)
以上是生活随笔為你收集整理的Find them, Catch them POJ - 1703(种类并查集)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Minimum Inversion Nu
- 下一篇: JAVA基础知识+基础代码