【題解】GreenJudge h166: F.逆序數對

題目敘述:http://www.tcgs.tc.edu.tw:1218/ShowProblem?problemid=h166
解題想法:DP (不需要用array紀錄)、Greedy

  • 變數cnt:紀錄連續的「>」個數。當遇到「<」時,重置cnt = 0。
  • 變數ans:累計最少逆序數對組數。
#include <iostream>
using namespace std;

int main() {
    int num, n, cnt;
    long long ans;
    string s;
    cin >> num;
    while (num--){
        cin >> n;
        cin >> s;
        cnt = 0; // 連續「>」個數
        ans = 0; // 累計最少逆序數對
        for (int i = 0; i < n-1; i++){
            if (s[i] == '>'){
                cnt++;
                ans += cnt;
            }else{
                cnt = 0;
            }
        }
        cout << ans << "\n";
    }
}
分享本文 Share with friends