RE求助

P5719 【深基4.例3】分类平均

Frank_Ron @ 2021-06-06 16:45:54

#include <bits/stdc++.h>
using namespace std;
int a[105];
int b[105];

int main() {
    int n, k, counti = 0, countj = 0;
    scanf("%d %d", &n, &k);
    for (int i = 1; i <= n; i++) {
        if (i % k == 0) {
            a[counti] = i;
            counti += 1;
        } else {
            b[countj] = i;
            countj += 1;
        }
    }

    int suma = 0;
    int counta = 0;
    double averagea;
    for (int j = 0; j < 105; j++) {
        suma += a[j];
        if (a[j] == 0) {
            counta = j;
            break;
        }
    }
    averagea = (float)suma / counta;
    printf("%.1f ", averagea);

    int sumb = 0;
    int countb = 0;
    double averageb;
    for (int k = 0; k < 105; k++) {
        sumb += b[k];
        if (b[k] == 0) {
            countb = k;
            break;
        }
    }
    averageb = (float)sumb / countb;
    printf("%.1f ", averageb);

    return 0;
}

by galfth @ 2021-06-06 17:36:10

@Frank_Ron 数组开成10005.


by Enterprise_E @ 2021-08-18 16:36:42

你这似乎复杂化了

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
    int n,k;
    long long na=0,nb=0;
    double sa=0,sb=0;
    cin>>n>>k;
    for(int i=1;i<=n;++i){
        if(i%k==0){
            sa+=i;
            na++;
        }
        else sb+=i;nb++;
    }
    printf("%.1f %.1f",sa/na,sb/nb);
    return 0;   
}

算法复杂度\theta(n)


|