Codeforces 補題 Educational Round 19

Problem-A

Given a positive integer n, find k integers (not necessary distinct)
such that all these integers are strictly greater than 1, and their
product is equal to n.

Input The first line contains two integers n and k (2 ≤ n ≤ 100000,
1 ≤ k ≤ 20).

Output If it’s impossible to find the representation of n as a product
of k numbers, print -1.

Otherwise, print k integers in any order. Their product must be equal
to n. If there are multiple answers, print any of them.

理性分析後這題不難,主要是求出可能的因子序列,然後將其縮減到合適長度就行。這裏有個坑就是剛開始爲了方便用來 i*i<=n 但實際上當n還有剩餘是,這部分是考慮不到的。例如測試數據爲 9999 3
那麼當i=11時,ii=121>n=101這裏寫圖片描述

#include <cstdio>
#include <iostream>

using namespace std;

const int maxn = 1e5 + 10;
int n,k,seq[maxn],sz;

int main(){
    sz=0;
    scanf("%d%d",&n,&k);
    for(int i=2;i<=n;i++)
        while(n%i==0){
            seq[sz++]=i;
            n /= i;
        }


    if(sz<k){
        printf("-1\n");
        return 0;
    }

    while(sz>k){
        int t=seq[sz-1]*seq[sz-2];
        sz-=2;
        seq[sz++]=t;
    }

    for(int i=0;i<sz;i++)
        printf("%d ",seq[i]);
    printf("\n");

    return 0;
}

Problem-B

You are given sequence a1, a2, …, an of integer numbers of length n.
Your task is to find such subsequence that its sum is odd and maximum
among all such subsequences. It’s guaranteed that given sequence
contains subsequence with odd sum.

Subsequence is a sequence that can be derived from another sequence by
deleting some elements without changing the order of the remaining
elements.

You should write a program which finds sum of the best subsequence.

Input The first line contains integer number n (1 ≤ n ≤ 105).

The second line contains n integer numbers a1, a2, …, an
( - 104 ≤ ai ≤ 104). The sequence contains at least one subsequence
with odd sum.

Output Print sum of resulting subseqeuence.

這題算是DP的一種吧,我是看了別人的答案纔有思路的,首先題目的目標是求出最大的子集奇數和,數據有正數和負數。首先應該把正數加到一起,看它是不是爲奇數,如果是奇數,那麼就一定是最大的。如果不是,那麼就應該考慮減掉裏面最小的正奇數,或者加上一個負奇數,總之就是在裏面權衡找到最大的奇數。

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

const int maxn = 1e5+5;

int main(){
    int n,a[maxn],sum=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
        if(a[i]>0)
            sum+=a[i];
    }
    if(sum&1) cout<<sum<<endl;
    else{
        int mn = 2e9;
        for(int i=0;i<n;i++)
            if(a[i]>0&&a[i]&1)
                mn = min(mn,a[i]);
        int ans = sum-mn;
        for(int i=0;i<n;i++)
            if(a[i]<0&&a[i]&1)
                ans = max(ans,sum+a[i]);
        cout<<ans<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章