列表

详情


NC24040. [USACO 2016 Feb S]Circular Barn

描述

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 n rooms, numbered clockwise from 1…n around the perimeter of the barn (3≤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 n 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 ci cows line up outside the door to room i, so ∑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 d doors consumes d2 energy, please determine the minimum amount of energy needed to distribute the cows so one ends up in each room.

输入描述

The first line of input contains n. Each of the remaining n lines contain c1…cn.

输出描述

Please write out the minimum amount of energy consumed by the cows.

示例1

输入:

10
1
0
0
2
0
0
1
2
2
2

输出:

33

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

Python3(3.9) 解法, 执行用时: 17ms, 内存消耗: 2848K, 提交时间: 2020-12-20 04:22:16

import sys

n = int(input())
arr = [0] * n
for i in range(n):
    arr[i] = int(input())

found = False
to_fill = to_be_filled = 0
for i in range(n):
    to_be_filled += 1
    to_fill += arr[i]
    if to_be_filled > to_fill:
        start = i + 1
        to_fill = to_be_filled = 0
        found = True

if not found:
    print(0)
    sys.exit()

arr += arr
total = 0
to_be_filled = 0
for i in range(start+n-1, start-1, -1):
    num = arr[i]
    if num > 0:
        for _ in range(num):
            total += to_be_filled ** 2
            to_be_filled -= 1
    to_be_filled += 1

print(total)

C++11(clang++ 3.9) 解法, 执行用时: 12ms, 内存消耗: 480K, 提交时间: 2020-02-26 23:52:40

#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int  n,i,s,l,x=1,t=1,w=0,a[N],g[N];
long long ans;
int main()
{
	cin>>n;
	for(i=1;i<=n;++i)
	{
		cin>>a[i];
		a[n+i]=a[i];
	}
	for(i=1;i<=2*n-1;++i)
	{
		if(s<0)
		s=0,x=i;
		s+=a[i]-1;
		if(s>ans)
		ans=s,l=x;
	}
	ans=0;
	for(i=l;i<=l+n-1;++i)
	{
		while(a[i]--)
		g[++w]=i;
		ans+=1LL*(i-g[t])*(i-g[t]);
		t++;
	}
	cout<<ans;
	return 0;
}

C++14(g++5.4) 解法, 执行用时: 9ms, 内存消耗: 376K, 提交时间: 2019-06-29 11:39:51

#include<stdio.h>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
int n,a[1100],at,x,te,ans;
int main(){
	ans=0x7fffffff;
	scanf("%d",&n);
	fo(i,0,n-1){
		scanf("%d",&x);
		fo(j,1,x) a[at++]=i;
	}
	fo(st,0,n-1){
		te=0;
		fo(i,0,n-1){
			x=(st+i-a[i])%n;
			if (x<0) x+=n;
			te+=x*x;
		}
		if (te<ans) ans=te;
	}
	printf("%d\n",ans);
	return 0;
}

上一题