码迷,mamicode.com
首页 > 编程语言 > 详细

【算法系列学习】codeforces D. Mike and distribution 二维贪心

时间:2017-04-24 22:56:05      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:isp   str   include   namespace   view   pac   test   using   gif   

http://codeforces.com/contest/798/problem/D

http://blog.csdn.net/yasola/article/details/70477816

对于二维的贪心我们可以先让它变成其中一维有序,这样只需要重点考虑另一维,就会简单很多。

首先,对于题目要求的选择元素之和两倍大与所有元素之和,我们可以转化为选择元素之和大于剩下的。然后我们可以将下标按照a从大到小排序。然后选择第一个,之后每两个一组,选择b大的一个,如果n是偶数再选择最后一个。

至于这样写的正确性:首先对于数组b,每一组选择的都是大的,而且还有多选的,所以一定比剩下的大。对于数组a,从第一个开始看,当前选择的,一定比下一组剩下的a大。所以这样贪心就一定正确。

技术分享
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<cmath>
 7 
 8 using namespace std;
 9 const int maxn=1e5+10;
10 struct node
11 {
12     int x;
13     int id;
14 }a[maxn],b[maxn];
15 int n;
16 bool cmp(const node& aa,const node& bb)
17 {
18     return aa.x>bb.x;
19 }
20 int main()
21 {
22     scanf("%d",&n);
23     for(int i=0;i<n;i++)
24     {
25         scanf("%d",&a[i].x);
26         a[i].id=i+1;
27     }
28     for(int i=0;i<n;i++)
29     {
30         scanf("%d",&b[i].x);
31         b[i].id=i+1;
32     }
33     printf("%d\n",n/2+1);
34     sort(a,a+n,cmp);
35     printf("%d",a[0].id);
36     for(int i=1;i<n;i+=2)
37     {
38         if(b[a[i].id-1].x>b[a[i+1].id-1].x)
39         {
40             printf(" %d",a[i].id);
41         }
42         else
43         {
44             printf(" %d",a[i+1].id);
45         }
46     }
47     printf("\n");
48     return 0;
49 }
View Code

 

【算法系列学习】codeforces D. Mike and distribution 二维贪心

标签:isp   str   include   namespace   view   pac   test   using   gif   

原文地址:http://www.cnblogs.com/itcsl/p/6759130.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!