Find them, Catch them POJ - 1703(种类并查集)
題意:
在這個城市里有兩個黑幫團(tuán)伙,現(xiàn)在給出N個人,問任意兩個人他們是否在同一個團(tuán)伙
1.輸入D x y代表x于y不在一個團(tuán)伙里
2.輸入A x y要輸出x與y是否在同一團(tuán)伙或者不確定他們在同一個團(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
分析:
這道題用的是種類并查集:并查集把給出的人分成幾個集合,每個集合之間的人的關(guān)系不確定,對同一個集合保存和本人不為同一隊的人,本著敵人的敵人便是朋友的原則,用并查集同一集合為同一隊,不同集合為不同隊。說的我自己都繞暈了,23333
1.首先特殊解很重要:當(dāng)N=2時他們屬于不同的幫派,因為題目有說兩個幫派至少有一個人。
2.
(1)只要輸入D,就將a,b兩個合并,歸在同一集合,并將改他們的關(guān)系。
(2)輸入A的時候判斷a,b是否合并過,如果兩個不屬于同一個集合的話就不能確定他們是否在同一個幫派。
(3)若合并過,即前面已經(jīng)出現(xiàn)過,則有確定關(guān)系即是否在同一幫派。此時只要判定其dp【】值是否相同,即為一個隊,為同一幫派,否則不在。
原因:我在把一個集合合并到另一個集合時,把x根節(jié)點的dp變成和y根節(jié)點dp相對的,(每次連兒子保證和父親不是一個幫派,同時更新父親)然后在查找的時候要修改dp值(注意回溯),因為生成的樹每一層和隔層的dp值是相對的(0和1),因為dp的值只能為0和1(只有兩個幫派),所以類別偏移用位運算
(4)若我太啰嗦,可參照 如下AC代碼,有步驟詳解:
總結(jié)
以上是生活随笔為你收集整理的Find them, Catch them POJ - 1703(种类并查集)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Minimum Inversion Nu
- 下一篇: JAVA基础知识+基础代码