题目链接
1400的 div 3 E题,难度不大。
题目大意:给出一个字符串,“ * ” 表示羊," . "是空地。让你用最小的操作数把所有的羊排成一排。每次操作可以让一只羊左移或者右移(当然前提是移动到的地方是空地)。
分析:题目题意好理解,思路也不难,稍微一推就出来了。
可以设排好序的第一个位置是x,第二个位置就是x + 1… 并且每只羊不能越过另一只羊。所以有了初始位置和末尾位置就可以列出来式子:(以sample1为例:**.*…) ∣ 1 − x ∣ + ∣ 2 − ( x + 1 ) ∣ + ∣ 4 − ( x + 2 ) ∣ \left | 1 - x \right | + \left | 2 - (x + 1) \right | + \left | 4 - (x + 2) \right | ∣1−x∣+∣2−(x+1)∣+∣4−(x+2)∣,即 ∣ 1 − x ∣ + ∣ 1 − x ∣ + ∣ 2 − x ∣ \left | 1 - x \right | + \left | 1 - x \right | + \left | 2 - x \right | ∣1−x∣+∣1−x∣+∣2−x∣。很明显,当x为1,1,2的中位数时,该式子最小。(注意开long long)
code:
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
#define int long long
const int N = 1e5 + 100;
const int INF = 0x3f3f3f3f;
void solve() {
int n;
vector<int> ve;
string s;
cin >> n >> s;
for (int i = 0; i < n; i++) {
if (s[i] == '*') {
ve.push_back(i + 1 - (ve.size()));
}
}
if (ve.size() == 0) {
cout << 0 << endl;
return;
}
sort(ve.begin(), ve.end());
int len = ve.size();
int ans = ve[len / 2];
int res = 0;
for (int i = 0; i < len; i++) {
res += abs(ve[i] - ans);
}
cout << res << endl;
}
signed main(int argc, char const *argv[]) {
int t;
cin >> t;
while (t--) solve();
return 0;
}