Zjnu Stadium HDU - 304 加权并查集
題意:
觀眾席圍成一圈。列的總數(shù)是300,編號(hào)為1–300,順時(shí)針計(jì)數(shù),我們假設(shè)行的數(shù)量是無(wú)限的。將有N個(gè)人去那里。他對(duì)這些座位提出了要求:這意味著編號(hào)A的順時(shí)針X距離坐著編號(hào)B。例如:A在第4列,X是2,那么B必須在第6列(6=4+2)。現(xiàn)在你的任務(wù)是判斷請(qǐng)求是否正確。
題目:
In 12th Zhejiang College Students Games 2007, there was a new stadium built in Zhejiang Normal University. It was a modern stadium which could hold thousands of people. The audience Seats made a circle. The total number of columns were 300 numbered 1–300, counted clockwise, we assume the number of rows were infinite.
These days, Busoniya want to hold a large-scale theatrical performance in this stadium. There will be N people go there numbered 1–N. Busoniya has Reserved several seats. To make it funny, he makes M requests for these seats: A B X, which means people numbered B must seat clockwise X distance from people numbered A. For example: A is in column 4th and X is 2, then B must in column 6th (6=4+2).
Now your task is to judge weather the request is correct or not. The rule of your judgement is easy: when a new request has conflicts against the foregoing ones then we define it as incorrect, otherwise it is correct. Please find out all the incorrect requests and count them as R.
Input
There are many test cases:
For every case:
The first line has two integer N(1<=N<=50,000), M(0<=M<=100,000),separated by a space.
Then M lines follow, each line has 3 integer A(1<=A<=N), B(1<=B<=N), X(0<=X<300) (A!=B), separated by a space.
Output
For every case:
Output R, represents the number of incorrect request.
Sample Input
10 10
1 2 150
3 4 200
1 5 270
2 6 200
6 5 80
4 7 150
8 9 100
4 8 50
1 7 100
9 2 100
Sample Output
2
Hint
Hint:
(PS: the 5th and 10th requests are incorrect)
思路
1.由于題中明確給出,編號(hào)A的順時(shí)針X距離坐著編號(hào)B,故x<300,當(dāng)我們用并查集找到一個(gè)祖宗節(jié)點(diǎn)時(shí),我們可以將該點(diǎn)看作原點(diǎn),將圈拉成直線看待。即可忽略成環(huán)。
2.b->a, a離”原點(diǎn)更近“
int f(int x) {if(x!=dp[x]){int t=dp[x];/*因?yàn)樵谶f歸找祖先的過(guò)程中,dp[x]的值會(huì)改變,而我們我們只需要找到距離x最近的點(diǎn),即可得到dp[x]到祖宗節(jié)點(diǎn)的距離。所以要記錄t的值*/dp[x]=f(dp[x]);num[x]+=num[t];}return dp[x]; }AC代碼
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int M=5e4+10; int dp[M],num[M]; int f(int x) {if(x!=dp[x]){int t=dp[x];dp[x]=f(dp[x]);/*因?yàn)樵谶f歸找祖先的過(guò)程中,dp[x]的值會(huì)改變,而我們我們只需要找到距離x最近的點(diǎn),即可得到dp[x]到祖宗節(jié)點(diǎn)的距離。所以要記錄t的值*/num[x]+=num[t];}return dp[x]; } bool dfs(int a,int b,int x) {int u=f(a),v=f(b);/*a->u,b->v*/if(u==v){if(num[a]+x!=num[b])/*b->a,又起點(diǎn)為父節(jié)點(diǎn)*/return true;return false;}dp[v]=u;num[v]=num[a]+x-num[b];return false; } int main() {int m,n;while(~scanf("%d%d",&m,&n)){int ans=0;for(int i=0;i<m;i++){dp[i]=i;num[i]=0;}while(n--){int a,b,x;/*設(shè)起點(diǎn)為祖宗節(jié)點(diǎn),則都指向起點(diǎn)b->a*/scanf("%d%d%d",&a,&b,&x);if(dfs(a,b,x))ans++;}printf("%d\n",ans);}return 0; }總結(jié)
以上是生活随笔為你收集整理的Zjnu Stadium HDU - 304 加权并查集的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 霰粒肿是怎么引起的?
- 下一篇: 蜘蛛牌 HDU - 1584(搜索——达