1. 程式人生 > >51nod 1307:繩子與重物

51nod 1307:繩子與重物

http fin cst iostream name 復雜度 總量 union namespace

51nod 1307:繩子與重物

題目鏈接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1307

題目大意:給定$n$條繩子,每條繩子有最大承重$C_i$,總量$W_i$和掛點$P_i$,問按順序掛最多掛幾條繩子.

並查集

考慮逆序掛繩子,若當前繩子最大承重小於實際承重,則將後面的繩子刪去.復雜度$O(n)$.

代碼如下:

 1 #include <cstdio>
 2 #include <iostream>
 3 using namespace std;
 4 int n,l,pre[50005
],tot[50005],w[50005]; 5 struct node{ 6 int maxw,w,p,id; 7 }a[50005]; 8 void init(){ 9 for(int i=0;i<=50000;++i) 10 pre[i]=i; 11 } 12 int Find(int x){ 13 return x==pre[x]?x:pre[x]=Find(pre[x]); 14 } 15 void Union(int a,int b){ 16 int x=Find(a),y=Find(b); 17 if(x!=y)pre[x]=y;
18 } 19 int main(void){ 20 init(); 21 scanf("%d",&n); 22 for(int i=n-1;i>=0;--i){ 23 scanf("%d%d%d",&a[i].maxw,&a[i].w,&a[i].p); 24 a[i].id=n-1-i; 25 } 26 for(int i=0;i<n;++i){ 27 int x=a[i].id,p=a[i].p; 28 tot[x]=a[i].maxw;
29 w[x]+=a[i].w; 30 while(tot[x]<w[x]&&l<=i){ 31 w[Find(a[l].id)]-=a[l].w; 32 l++; 33 } 34 if(p!=-1){ 35 Union(x,p); 36 w[p]+=w[x]; 37 } 38 } 39 printf("%d\n",n-l); 40 }

51nod 1307:繩子與重物