ZeroJudge B112: 高中運動會

題目敘述

本題採EOF方式收資料,每筆資料第一行有一個正整數N,接下來會有N行,每行會有一個正整數,代表某一個學校的校隊有幾個人。每個學校的人都需要平均分配到不同隊,要求輸出可以最多分到幾隊。


範例輸入 #1

3

12

16

20

4

400

200

150

625

範例輸出 #1

4

25


解題思路

收資料的時候先把收到數字的因數存到一個Map中,然後建立一個Vector<Map>的資料結構將每個學校的因數Map都存放進去。之後使用Auto跑第一個學校的Map的For迴圈,並且和其他學校的Map比較看有沒有出現一樣的因數,如果所有學校都有相同的因數則先將答案設為這個因數,取最大值。

解題程式碼如下 (僅供參考):

#include <iostream>
#include <vector>
#include <math.h>
#include <map>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N;
    while (cin >> N)
    {
        vector<int>num;
        vector<map<int, int>>vMAP;
        for (int i = 0; i<N; i++)
        {
            int tmp;
            cin >> tmp;
            num.push_back(tmp);
            map<int, int>MAP;
            for (int j = 2; j<int(sqrt(tmp))+1; j++)
            {
                if (tmp % j == 0)
                {
                    MAP[j]++;
                    MAP[tmp/j]++;
                }
            }
            vMAP.push_back(MAP);
        }
        int ans = 1;
        for (auto it:vMAP[0])
        {
            int factor = it.first;
            bool ok = true;
            for (int i = 1; i<N; i++)
            {
                if (vMAP[i][factor] == 0)
                {
                    ok = false;
                    break;
                }
            }
            if (ok) ans = factor;
        }
        cout << ans << "\n";
    }
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge A263: 日期差幾天