009 Zero Array (CF #577div2 B)

本文分享了Codeforces A题ZeroArray的解题思路及代码实现。通过分析题目要求,提出了两个关键条件:数列总和需为偶数且最大值须超过剩余数之和。并提供了有效的算法解决方案。

第一次打CF只过了一A题 RP-81……
Zero Array
题目链接
大意:
有一系列数字,每次选两个数同时减1,令每个数都变成0。

In one operation you can choose two elements ai and aj (i≠j) and decrease each of them by one.

这个"by one" 我理解成了一个被另一个减去"by the other" 不然这个题肯定能做出来,也不至于钻牛角尖浪费时间。言归正传来看这道题,CF给的tag是greedy和math。
此题从数学方面入手思路也很清晰,无非就下面两个条件:

  • n个数之和为偶数(显然)
  • 最大值要比其余几个数之和要大
    (2)的充分性证明暂时还没想到 CF的讨论板上目前也没看到合理的证明 先占坑,日后补

代码如下:

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    ll n, m, a, s;
    int main()
    {
        ios_base::sync_with_stdio(false);
        cin>>n;
        for (ll i=1; i<=n; i++)
        {
            cin>>a;
            s+=a;
            m=max(m, a);
        }
        if (s%2==1 || s<2*m)
        {
            cout<<"NO";
            return 0;
        }
        cout<<"YES";
        return 0;
    }

末尾杂谈一下自己走的弯路。
重新看清题后我打算模拟暴力过,具体思路如下:
①预处理排除所有总和非偶数的数组
②对于任意数组排序后有如下操作,递归调用②直至全为0或仅余下一个数

  • ①若最大值=最小值,必满足条件
  • ②若有奇数项,最大值减去最小值,最小值归零
  • ③若有偶数项,所有值减去最小值(包括最小值)

按以上算法能过大多数点,但是时间复杂度高,会TLE,不知道能不能优化,望读者指教了

import os #import sys import numpy as np import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import Conv2D, Conv1D, ZeroPadding2D from tensorflow.keras.layers import Input from tensorflow.keras.layers import Lambda, multiply from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import MeanSquaredError #sys.path.append(&#39;../data&#39;) #sys.path.append(&#39;../models&#39;) from data.data_generator import DIV2KDatasetMultiple as Database import h5py nodes = {&#39;in&#39;: [&#39;rec_luma&#39;, &#39;rec_boundary&#39;], &#39;out&#39;: [&#39;org_chroma&#39;]} # Scheme 1 architecture class get_att(tf.keras.layers.Layer): def __init__(self): super(get_att, self).__init__() def call(self,inputs): f1, f2 = inputs # att_x [bs, N, N, h], att_b [bs, b, h] f1 = K.reshape(f1, shape=[K.shape(f1)[0], K.shape(f1)[1] * K.shape(f1)[2], K.shape(f1)[-1]]) y = tf.matmul(f1, f2, transpose_b=True) return K.softmax(y / 0.5, axis=-1) class apply_att(tf.keras.layers.Layer): def __init__(self): super(apply_att, self).__init__() def call(self, inputs): f1, f2, f3 = inputs # att [bs, NxN, b], b [bs, b, D], x_out [bs, N, N, D] y = K.batch_dot(f1, f2) # [bs, NxN, D] return K.reshape(y, shape=K.shape(f3)) class CrossIntraModel: def __init__(self, cf): self._cf = cf self.name = "multi" self.model = self.get_model() def attentive_join(self, x, b): att_b = Conv1D(self._cf.att_h, kernel_size=1, strides=1, padding=&#39;same&#39;, activation=&#39;relu&#39;, name=&#39;att_b&#39;)(b) att_x = Conv2D(self._cf.att_h, kernel_size=1, strides=1, padding=&#39;same&#39;, activation=&#39;relu&#39;, name=&#39;att_x&#39;)(x) x_out = Conv2D(b.shape[-1], kernel_size=1, strides=1, padding=&#39;same&#39;, activation=&#39;relu&#39;, name=&#39;att_x1&#39;)(x) att = get_att()([att_x, att_b]) b_out =apply_att()([att, b, x_out]) return multiply([x_out, b_out]) def get_model(self): l_input = Input((None, None, 1), name=&#39;l_input&#39;) b_input = Input((None, 1), name=&#39;b_input&#39;) # boundary branch b = Conv1D(self._cf.bb1, kernel_size=1, strides=1, padding=&#39;same&#39;, activation=&#39;relu&#39;, name=&#39;b1&#39;)(b_input) b = Conv1D(self._cf.bb2, kernel_size=1, strides=1, padding=&#39;same&#39;, activation=&#39;relu&#39;, name=&#39;b2&#39;)(b) # luma branch x = ZeroPadding2D((2, 2))(l_input) x = Conv2D(self._cf.lb1, kernel_size=3, strides=1, padding=&#39;valid&#39;, activation=None, name=&#39;x1&#39;)(x) x = Conv2D(self._cf.lb2, kernel_size=3, strides=1, padding=&#39;valid&#39;, activation=&#39;relu&#39;, name=&#39;x2&#39;)(x) # trunk branch t = self.attentive_join(x, b) t = Conv2D(self._cf.tb, kernel_size=3, strides=1, padding=&#39;same&#39;, activation=None, name=&#39;t2&#39;)(t) output = Conv2D(2, kernel_size=1, strides=1, padding=&#39;same&#39;, activation=&#39;linear&#39;, name=&#39;out&#39;)(t) return Model([l_input, b_input], output) @staticmethod def norm_mse(y_true, y_pred): return MeanSquaredError(y_true * 255, y_pred * 255) def create_dataset(self, features, labels): dataset = tf.data.Dataset.from_tensor_slices((features, labels)) dataset = dataset.shuffle(buffer_size=len(features)).batch(self._cf.batch_size).prefetch(tf.data.AUTOTUNE) return dataset def train(self): print("Training model: %s" % self.name) output_path = os.path.join(self._cf.output_path, self._cf.model) if not os.path.exists(self._cf.output_path): os.mkdir(self._cf.output_path) if not os.path.exists(output_path): os.mkdir(output_path) train_data_path = os.path.join(self._cf.data_path, &#39;train&#39;, "4x4.h5") train_data_in = h5py.File(train_data_path) train_data_out = h5py.File(train_data_path) train_data_in = [train_data_in[k] for k in nodes[&#39;in&#39;]] train_data_out = [train_data_out[k] for k in nodes[&#39;out&#39;]] train_ds = self.create_dataset(np.array(train_data_in), np.array(train_data_out)) checkpoint = ModelCheckpoint(output_path + "/.weights.h5", monitor=&#39;val_loss&#39;, verbose=0, mode=&#39;min&#39;, save_best_only=True, save_weights_only=True) early_stop = EarlyStopping(monitor=&#39;val_loss&#39;, mode="min", patience=self._cf.es_patience) tensorboard = TensorBoard(log_dir=output_path) callbacks_list = [checkpoint, early_stop, tensorboard] optimizer = Adam(self._cf.lr, self._cf.beta) nb_block_shapes = len(self._cf.block_shape) self.model.compile(optimizer=optimizer, loss=self.norm_mse, metrics=[&#39;accuracy&#39;]) self.model.summary() self.model.fit(train_ds, epochs=self._cf.epochs )
最新发布
05-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值