a423中等同步模擬・以鄰接關係累計人口變化

APCS 2020/10:人口遷移 (ZeroJudge f313)

所有移出量從當日舊人口計算,累加到另一份陣列後才換日。

前往題目練習 →回報教學錯誤時間 O(RC+mRC);空間 O(RC),每座城市的鄰居至多四個。

這題在學什麼

先只為非負格建立城市編號,並預先列出上下左右真正存在的鄰居。某城市一天對每個鄰居都送出 floor(人口/k) 人,因此總移出是這個商乘以鄰居數;沒有城市或地圖外的方向不能移出。

每天複製舊人口為 next,再對每座城市從 next 扣掉總移出、向各鄰居的 next 加上同樣數量。所有商都讀自舊人口,不會讓今天收到的人在今天再次搬走。每條遷移都一減一加,故總人口守恆;k≥4 且鄰居至多 4,也保證不會移出超過原人口。

完成 m 天後只在城市人口中取最小與最大,不能把 -1 的非城市一起比較。若整張圖皆為非城市,題敘未定義極值;程式將空集合約定輸出 0、0。

Step-by-step animation

公開範例:k=4,模擬一天

回報動畫錯誤
步驟 1 / 3

建立城市鄰居

人口 10 的城市鄰接 2 與 5;右下人口 2 的城市沒有鄰居。

10
2
非城市
5
非城市
2
總人口
19
各城市每邊移出
2,0,1,0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false); cin.tie(nullptr);
    int R,C,k,days; cin >> R >> C >> k >> days;
    vector<vector<int>> id(R,vector<int>(C,-1));
    vector<int> population;
    for (int r=0;r<R;r++) for (int c=0;c<C;c++) {
        int x; cin >> x;
        if (x>=0) { id[r][c]=population.size(); population.push_back(x); }
    }
    vector<vector<int>> adj(population.size());
    int dr[4]={-1,1,0,0}, dc[4]={0,0,-1,1};
    for (int r=0;r<R;r++) for (int c=0;c<C;c++) {
        if (id[r][c]<0) continue;
        for (int d=0;d<4;d++) {
            int nr=r+dr[d],nc=c+dc[d];
            if (nr>=0 && nr<R && nc>=0 && nc<C && id[nr][nc]>=0)
                adj[id[r][c]].push_back(id[nr][nc]);
        }
    }
    while (days--) {
        vector<int> next=population;
        for (int u=0;u<(int)population.size();u++) {
            int share=population[u]/k;
            next[u]-=share*(int)adj[u].size();
            for (int v:adj[u]) next[v]+=share;
        }
        population.swap(next);
    }
    if (population.empty()) cout << "0\n0\n";
    else cout << *min_element(population.begin(),population.end()) << '\n'
              << *max_element(population.begin(),population.end()) << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多