題目鏈接:見這里 題意:給了兩個數組a, b。現在你可以交換a,b數組的任意兩個數,問最少交換多少次,可以讓a,b數組里面每個數的出現次數相同,不能達到上述狀態輸出”-1”。其中a,b數組里面每個數是1-5. 解法:模擬,想想就可以知道如果對于1-5這每個數,如果出現次數之和為奇數那么肯定不能達到目標。否則答案就是就是所有數出現次數的差除以2之和,并且最后答案再除以2。不這樣計算,直接貪心模擬也是可以的。
//CF 779A#include <bits/stdc++.h>using namespace std;const int maxn = 100;int n, x, cnt1[6], cnt2[6];int main(){ scanf("%d", &n); for(int i = 1; i <= n; i++){ int x; scanf("%d", &x); cnt1[x]++; } for(int i = 1; i <= n; i++){ int x; scanf("%d", &x); cnt2[x]++; } for(int i = 1; i <= 5; i++){ if((cnt1[i]+cnt2[i])&1){ puts("-1"); return 0; } } int ans = 0; for(int i = 1; i <= 5; i++){ ans += abs(cnt1[i] - cnt2[i]) / 2; } ans /= 2;新聞熱點
疑難解答