51nod|51nod 1117 聪明的木匠 (贪心)

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1117
跟挑战程序书上例题一样,将要切割的n断木板,分别对应二叉树树的叶子节点,则切割的总开销为木板的长度×节点的深度,可以画图理解,那么最短的木板(L1)应当是深度最大的叶子节点之一,次短的板(L2)和它是兄弟节点,由一块长度是(L1+L2) 的木板切割而来,这样可以变成(n-1)块木板,然后递归求解到n==1。
书上贪心部分用的是O(n×n) 的算法在这里会超时,需要2.4节优先队列O(NlogN)的算法。

1 #include 2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 #include 16 17 #define CL(arr, val)memset(arr, val, sizeof(arr)) 18 19 #define ll long long 20 #define inf 0x7f7f7f7f 21 #define lc l,m,rt<<1 22 #define rc m + 1,r,rt<<1|1 23 #define pi acos(-1.0) 24 25 #define L(x)(x) << 1 26 #define R(x)(x) << 1 | 1 27 #define MID(l, r)(l + r) >> 1 28 #define Min(x, y)(x) < (y) ? (x) : (y) 29 #define Max(x, y)(x) < (y) ? (y) : (x) 30 #define E(x)(1 << (x)) 31 #define iabs(x)(x) < 0 ? -(x) : (x) 32 #define OUT(x)printf("%I64d\n", x) 33 #define lowbit(x)(x)&(-x) 34 #define Read()freopen("a.txt", "r", stdin) 35 #define Write() freopen("b.txt", "w", stdout); 36 #define maxn 1000000000 37 #define N 50005 38 using namespace std; 39 40 int L[N]; 41 int main() 42 { 43// Read(); 44int n; 45long long ans=0; 46scanf("%d",&n); 47for(int i=0; i1) 49{ 50int m1=0,m2=1; 51if(L[m1]>L[m2]) swap(m1,m2); 52for(int i=2; iL[i]) 55{ 56m2=m1; 57m1=i; 58} 59else if(L[m2]>L[i]) 60{ 61m2=i; 62} 63} 64//printf("%d %d\n",L[m1],L[m2]); 65int t=L[m1]+L[m2]; 66ans+=t; 67if(m1==n-1) swap(m1,m2); 68L[m1]=t; 69L[m2]=L[n-1]; 70n--; 71} 72printf("%lld\n",ans); 73return 0; 74 }

【51nod|51nod 1117 聪明的木匠 (贪心)】优化后的代码:每次只需要选择长度最小的两块木板,则用优先队列从小到大排序,每次把取出来的两块木板之和压进队列即可。
1 #include 2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 //#include 15 #include 16 17 #define CL(arr, val)memset(arr, val, sizeof(arr)) 18 19 #define ll long long 20 #define inf 0x7f7f7f7f 21 #define lc l,m,rt<<1 22 #define rc m + 1,r,rt<<1|1 23 #define pi acos(-1.0) 24 25 #define L(x)(x) << 1 26 #define R(x)(x) << 1 | 1 27 #define MID(l, r)(l + r) >> 1 28 #define Min(x, y)(x) < (y) ? (x) : (y) 29 #define Max(x, y)(x) < (y) ? (y) : (x) 30 #define E(x)(1 << (x)) 31 #define iabs(x)(x) < 0 ? -(x) : (x) 32 #define OUT(x)printf("%I64d\n", x) 33 #define lowbit(x)(x)&(-x) 34 #define Read()freopen("a.txt", "r", stdin) 35 #define Write() freopen("b.txt", "w", stdout); 36 #define maxn 1000000000 37 #define N 50005 38 using namespace std; 39 40 int L[N]; 41 priority_queue, greater >que; 42 int main() 43 { 44//Read(); 45int n; 46scanf("%d",&n); 47for(int i=0; i1) 54{ 55int l1,l2; 56l1=que.top(); 57que.pop(); 58l2=que.top(); 59que.pop(); 60ans+=l1+l2; 61que.push(l1+l2); 62} 63printf("%lld\n",ans); 64return 0; 65 }

转载于:https://www.cnblogs.com/nowandforever/p/4421844.html

    推荐阅读