1. 程式人生 > >Mike and distribution CodeForces - 798D (貪心+思維)

Mike and distribution CodeForces - 798D (貪心+思維)

題目連結

TAG: 這是我近期做過最棒的一道貪心思維題,不容易想到,想到就出乎意料。

題意:給定兩個含有N個正整數的陣列a和b,讓你輸出一個數字k ,要求k不大於n/2+1,並且輸出k個整數,範圍為1~n的不重複數字,

要求這k個數字為下標的對應a和b中的數的和乘以2的值  分別大於a和b 的陣列總和。

思路:首先對a進行降序排序,然後輸出最大值的下標,隨後進行幅度為2的列舉,對排序後的a2~an進行選擇性輸出下標,(注意,排序的時候用一個新陣列開兩個變數,一個index,一個v進行排序,可以用結構體,也可以用pair)

那麼怎麼進行選擇性排序呢,由於要求的是這k的數的和*2大於總和,那麼如果每兩個數選取了一個大的,那麼選出來的n/2+1個數的和*2一定大於原陣列總和,至於為什麼可以自行思考。

時間複雜度為O ( n*log n  )  ,,  非常好的一個貪心題目,思想可以抽象為把n個數分為 n/2的小集合,從每一個小子集中選大的那個數,那麼總和*2一定大於全集的和。

附上程式碼:

 

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include 
<map> #include <set> #include <vector> #define rep(i,x,n) for(int i=x;i<n;i++) #define repd(i,x,n) for(int i=x;i<=n;i++) #define pii pair<int,int> #define pll pair<long long ,long long> #define gbtb std::ios::sync_with_stdio(false) #define MS0(X) memset((X), 0, sizeof((X))) #define
MSC0(X) memset((X), '\0', sizeof((X))) #define pb push_back #define mp make_pair #define fi first #define se second #define gg(x) getInt(&x) using namespace std; typedef long long ll; inline void getInt(int* p); const int maxn=1000010; const int inf=0x3f3f3f3f; /*** TEMPLATE CODE * * STARTS HERE ***/ int n; ll a[maxn]; ll b[maxn]; struct node { int id; ll v; }c[maxn]; bool cmp(node a,node b) { return a.v>b.v; } int main() { scanf("%d",&n); repd(i,1,n) { scanf("%lld",&a[i]); c[i].v=a[i]; c[i].id=i; } repd(i,1,n) { scanf("%lld",&b[i]); } sort(c+1,c+1+n,cmp); printf("%d\n",n/2+1); printf("%d ",c[1].id ); for(int i=2;i<=n;i+=2) { if(i<n) { if(b[(c[i].id)]>b[c[i+1].id]) { printf("%d ", c[i].id); }else { printf("%d ",c[i+1].id); } }else { printf("%d",c[i].id ); } } return 0; } inline void getInt(int* p) { char ch; do { ch = getchar(); } while (ch == ' ' || ch == '\n'); if (ch == '-') { *p = -(getchar() - '0'); while ((ch = getchar()) >= '0' && ch <= '9') { *p = *p * 10 - ch + '0'; } } else { *p = ch - '0'; while ((ch = getchar()) >= '0' && ch <= '9') { *p = *p * 10 + ch - '0'; } } }