Uva-12166 Equilibrium Mobile

題目鏈接:Equilibrium Mobile

題目大意:給一個樹形結構的天平,求能使整個天平平衡的最少的對砝碼的更換次數。

解題思路:要使天平平衡最後情況一定是以某個砝碼作爲基準。枚舉砝碼,並記錄不改變該砝碼使天平平衡的情況下,天平的總權值。最後將所有砝碼的數量減去最大次數的最終狀態的值,即爲最小的修改數。

代碼如下:

#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 2e4 + 15;

map<ll, int> mp;
int sum, t;
string s;

void DFS(int l, int r, int dep){
    if(s[l] == '['){
        int cnt = 0;
        for(int i = l + 1; i < r; i++){
            if(s[i] == '[') cnt++;
            if(s[i] == ']') cnt--;
            if(s[i] == ',' && !cnt){
                DFS(l + 1, i - 1, dep + 1);
                DFS(i + 1, r - 1, dep + 1);
            }
        }
    }   
    else{
        ll w = 0;   
        for(int i = l; i <= r; i++) w = w * 10 + s[i] - '0';
        sum++; mp[w << dep]++;
    }
    return;
}

int main(){
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);
    cin >> t;
    while(t--){
        cin >> s;
        mp.clear();
        sum = 0;
        DFS(0, s.size() - 1, 0);
        int ma = -1;
        for(auto e : mp) ma = max(ma, e.second);
        int ans = sum - ma;
        cout << ans << endl;
    } 
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章