a552簡單有向需求的反向計數
CPE:Foreign Exchange (UVa 10763)
逐對比較兩個方向的學生數,保留重複需求的次數。
解題思路
將每位學生的 (A,B) 當成有向需求,累計出現次數。所有學生都能配對,若且唯若對每一對地點都有 count(A,B)=count(B,A),因為每個 A→B 只能消耗一個 B→A。
用有序映射或雜湊表保存這些次數,讀完後檢查每個鍵的反向鍵。只比較各地出入總數並不足夠,例如1→2、2→3、3→1每地流量平衡,卻沒有任何反向對象。n=0 結束,每筆只印 YES 或 NO。
Step-by-step animation
示意:1→2、1→2、2→1、2→1
步驟 1 / 3
讀兩筆正向
(1,2) 累計2人,反向尚無。
(1,2):2
(2,1):0
- 未配對差
- 2
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
while (cin >> n && n) {
map<pair<int, int>, int> count;
while (n--) {
int a, b;
cin >> a >> b;
++count[{a, b}];
}
bool ok = true;
for (const auto &[key, value] : count) {
auto it = count.find({key.second, key.first});
if (it == count.end() || it->second != value) {
ok = false;
break;
}
}
cout << (ok ? "YES" : "NO") << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。