Codeforces Round #719 (Div. 3) E题- Arranging The Sheep

传送门:Problem - E - Codeforces

官方题解:

Let's denote by kk the number of sheep in the string, and by x1,x2,…,xkx1,x2,…,xk (1≤x1<x2<…<xk≤n1≤x1<x2<…<xk≤n) their positions in the string.

Note that in the optimal solution the sheep with the number m=⌈n2⌉m=⌈n2⌉ will not make moves. This can be proved by considering the optimal solution in which the sheep with the number mm makes at least one move and come to the conclusion that this solution is not optimal. Consider sheep with numbers from i=1i=1 to nn. Then the final position of the ii-th sheep will be xm−m+ixm−m+i, and the answer will be ∑i=1k|xi−(xm−m+i)|∑i=1k|xi−(xm−m+i)|.

(自行翻译)

我的代码:

Codeforces Round #719 (Div. 3)  E题- Arranging The Sheep
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--) {
        int n;
        cin>>n;
        char s[n];
        scanf("%s",s);
        int a[n],l=0;
        for(int i=0;i<n;i++) {
            if(s[i]=='*') {
                a[l++]=i;
            }
        }
        long long sum=0;
        for(int i=0;i<l;i++) {
            sum+=abs(a[i]-(a[]-l/2+i));
        }
        cout<<sum<<endl;
    }
    return 0;
}
View Code

 

上一篇:Java之拷贝


下一篇:Codeforces Round #719 (Div. 3) E. Arranging The Sheep(中位数)