安徽大學2019 ACM實驗室公開賽 部分題解

URL:https://ac.nowcoder.com/acm/contest/2720

A.素數分佈

https://ac.nowcoder.com/acm/contest/2720/A

打個線性篩表,直接求和輸出即可。

AC代碼:

#include <iostream>
#include <cstring>
using namespace std;
const int N = 100005;
int num[N], prim[N];
int pn = 0;
void table(){
    memset(num, -1, sizeof(num));
    for(int i = 2;i < N;i++){
        if(num[i]) prim[pn++] = i;
        for(int j = 0;j < pn && 1LL*i*prim[j] < N;j++){
            num[i*prim[j]] = 0;
            if(i % prim[j] == 0) break;
        }
    }
}


int main() {
    int T;
    cin >> T;
    int n;
    table();
    while(T--) {
        cin >> n;
        int ans = 0;
        for(int i = 2;i<=n;i++) if(num[i]) ans++;
        cout << ans << endl;
    }


    return 0;
}

B.食物分配

先將食物從小到大排序,判定條件爲是否存在兩份小的食物之和等於稍大的兩份食物,即可。

AC代碼:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100005;
int T;
int A[4];
int main() {
    cin >> T;
    while(T--) {
        for(int i = 0; i < 4; i++) cin >> A[i];
        sort(A,A+4);
        int ans1 = A[0] + A[1];
        if(A[0] + A[1] == A[2] && A[2] == A[3]) {
            cout << A[3] << endl;
        }else {
            cout << -1<<endl;
        }
    }
    return 0;
}

 

C.AHUICPC(easy version)

數據範圍很小,只需要在n==10的時候多加一個A即可。

#include <iostream>
using namespace std;
int n;
int main() {
    cin >> n;
    if(n<10) {
        cout <<"AHU";
        while(n--) cout << "I";
        cout << "CPC" <<endl;
    }
    else {
        cout << "AAHUIIIIICPC"<<endl;
    }

    return 0;
}

 

D.不定方程

實際上是求兩者最小公倍數LCM的相關係數,並且可以知道,a和b必然是互質的,否則即不存在。而若兩者互質,交換二者即可。

AC代碼

#include<iostream>
using namespace std;
typedef long long LL ;
LL gcd(LL a,LL b)
{
    return b ? gcd(b,a%b):a;
}
int main()
{
    int n;
    cin >> n;
    while(n-- ) {
        LL a, b;
        cin >> a >> b;
        LL gcd1 = gcd(a,b);
        LL lcm1 =  a* b / gcd1;
        if(gcd(a,b)!=1) cout << -1 << endl;
        else cout << lcm1/a << " " << lcm1/b << " " << lcm1 << endl;
    }
    return 0;
}

 

F.蕊蕊上學

概率分佈,在a時間段內上車的概率爲(a/a+b),b時間段內爲(b/a+b),數學期望即爲(a^2+b^2)/(a+b)

AC代碼

#include<iostream>
using namespace std;
double a, b;
int main() {
    cin >> a >> b;
    double c = (a*a + b*b) / (a+b);
    printf("%.2lf\n",c);
    
    return 0;
}

 

H.無盡大軍

這題要用到唯一分解定理,將問題抽象爲從1開始,要麼耗費2點翻倍, 要麼耗費1點實現上一個願望。即

\Sigma a_i = n 即n的質因數分解。

AC代碼

#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
ll n;
int main() {
    cin >> n;
    ll num = 0;
    for(ll i = 2; i*i <= n; i++) {
        while(n % i == 0) {
            num += i;
            n /= i;
        }
    }
    if(n!=1) num += n;
    cout << num << endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章