当前位置: 代码迷 >> 综合 >> CF1520E Arranging The Sheep
  详细解决方案

CF1520E Arranging The Sheep

热度:35   发布时间:2023-12-02 01:43:46.0

题目描述

You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length nn , consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.

For example, if n=6n=6 and the level is described by the string "**.*..", then the following game scenario is possible:

  • the sheep at the 4 position moves to the right, the state of the level: "**..*.";
  • the sheep at the 2 position moves to the right, the state of the level: "*.*.*.";
  • the sheep at the 1 position moves to the right, the state of the level: ".**.*.";
  • the sheep at the 3 position moves to the right, the state of the level: ".*.**.";
  • the sheep at the 2 position moves to the right, the state of the level: "..***.";
  • the sheep are lined up and the game ends.

For a given level, determine the minimum number of moves you need to make to complete the level.

输入格式

The first line contains one integer tt ( 1≤t≤10^4 ). Then tt test cases follow.

The first line of each test case contains one integer nn ( 1≤n≤10^6 ).

The second line of each test case contains a string of length nn , consisting of the characters '.' (empty space) and '*' (sheep) — the description of the level.

It is guaranteed that the sum of nn over all test cases does not exceed 10^6106 .

输出格式

For each test case output the minimum number of moves you need to make to complete the level.

题意翻译

一共有 t 组数据,每组数据第一行为 n ,为字符串长度,下一行为一个字符串(只有 ' . ' 和 ' * '字符),每次可以向右或者向左移动 ‘ * ’ 字符,求把所有的 ' * ' 字符连起来的最小移动次数

输入输出样例

输入 #1复制

5
6
**.*..
5
*****
3
.*.
3
...
10
*.*...*.**

输出 #1复制

1
0
0
0
9

思路

有多种移动方式,全部向左,全部向右,或向最中间的*号靠拢

以10

    *。*。。。*。**        为例

全部向左

1+4+6+5=16

全部向右

1+4+5=10

向中靠拢

3+4+1+1=9

可知向最中间*号靠拢所需移动次数最少

则需知道所有*号的下标和最中间*号的下标

代码

#include <stdio.h>
#include <cmath>
#include <iostream>
using namespace std;
int main() {int t;cin>>t;while (t--) {long long int m=0;    //*号个数long long int mid;    //标记最中间*号long long int n;cin>>n;char a[n+3];long long int b[n+3];    //记录每个*的下标for (long long int i=0;i<n;i++) {cin>>a[i];}for (long long int i=0;i<n;i++) {	//记录每个*的下标 if (a[i]=='*') {b[m++]=i;}}if (m==0) {	//没有*号 cout<<'0'<<endl;continue;}if (m==n) {	//都是*号 cout<<'0'<<endl;continue;}long long int ans=0;mid=m/2;for (long long int i=0;i<m;i++) {ans=ans+abs(b[mid]-b[i])-abs(mid-i);}cout<<ans<<endl;}return 0;
}

abs()函数为取整型int的绝对值

abs( b [ mid ] - b [ i ]  )为当前*号移到最中间*号左右的距离

还需减去abs( mid - i ) 即已经移过去的*号个数

注意:

要开long long int ,不然会爆