P3137 [USACO16FEB]圆形谷仓Circular Barn_Silver
题目描述
Being a fan of contemporary architecture, Farmer John has built a new barn in the shape of a perfect circle. Inside, the barn consists of a ring of nn rooms, numbered clockwise from 1 \ldots n1…n around the perimeter of the barn (3 \leq n \leq 10003≤n≤1000). Each room has doors to its two neighboring rooms, and also a door opening to the exterior of the barn.
Farmer John owns nn cows, and he wants exactly one cow to end up in each room in the barn. However, the cows, being slightly confused, line up at haphazard doors, with possibly multiple cows lining up at the same door. Precisely c_ici cows line up outside the door to room ii, so \sum c_i = n∑ci=n.
To manage the process of herding the cows so that one cow ends up in each room, Farmer John wants to use the following approach: each cow enters at the door at which she initially lined up, then walks clockwise through the rooms until she reaches a suitable destination. Given that a cow walking through dd doors
consumes d^2d2 energy, please determine the minimum amount of energy needed to distribute the cows so one ends up in each room.
给定一个环长为n的环上每个点上有aia_i只牛,每只牛可以在环上顺时针移动,代价为移动距离的平方,问将环上每个节点上都有一只牛的代价是多少
输入输出格式
输入格式:
The first line of input contains nn. Each of the remaining nn lines contain
c_1 \ldots c_nc1…cn.
输出格式:
Please write out the minimum amount of energy consumed by the cows.
输入输出样例
10
1
0
0
2
0
0
1
2
2
2
33
思路:
贪心。a^2+b^2<(a+b)^2
奶牛不能越过位置行走,只能走到下一位,在走到下一位。
上图中红色路线的代价为2小于橙色路线的代价。
#include<queue> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; priority_queue<int,vector<int>,greater<int> >que; int a[2010]; int n,ans=1e9; int main(){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); a[n+i]=a[i]; } for(int i=1;i<=n;i++){ int flag=0,cnt=0; for(int j=i;j<=i+n-1;j++){ if(a[j]==0&&que.size()==0){ flag=1; break; } int x=a[j]; while(x){ que.push(j);x--; } int now=que.top();que.pop(); cnt+=(j-now)*(j-now); } if(flag==1) continue; ans=min(ans,cnt); } cout<<ans; }