POJ 题目1455Crazy tea party(数学)

Crazy tea party
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 7164 Accepted: 4864

Description

n participants of << crazy tea party >> sit around the table. Each minute one pair of neighbors can change their places. Find the minimum time (in minutes) required for all participants to sit in reverse order (so that left neighbors would become right, and right - left).

Input

The first line is the amount of tests. Each next line contains one integer n (1 <= n <= 32767) - the amount of crazy tea participants.

Output

For each number n of participants to crazy tea party print on the standard output, on a separate line, the minimum time required for all participants to sit in reverse order.

Sample Input

3
4
5
6

Sample Output

2
4
6

Source

Southeastern Europe 2003

题意:n个人围到一个圆桌上,每次每个人可以旁边的人交换位置,问最后多少次后每个人的左右都相反

思路:http://m.blog.csdn.net/blog/u010893129/21127153

大家都清楚假定是一排的情况下:

1 2 3 4 5 6 7

如果位置交换后:

7 6 5 4 3 2 1

需要经过n*(n-1)/2次交换(冒泡法进行交换)

 

现在情况是环形,试问能不能将环拆分成两个线性,然后进行交换,再拼接在一起。

举例如下:

1 2 3 4 5 6 77后面又是1

如果分成1 2 3 ,4 5 6 7两部分,分别进行逆序,然后连接,是不是满足条件呢?

交换后3  2 1, 7 6 5 4

连接后为:3  2 1 7 6 5 4,在环路中,其实位置更改后为7654321,是满足条件的。

那么题目得解:

现在问题是假定环形的长度是N,如果进行截图,才能使得交换次数是最少的呢?
假定N的环形,分成一个长度为k,另一个长度是N-k的线段。

那么需要交换的次数为:

k*(k-1)/2

(N-k)*(N-k-1)/2

相加后就是需要交换的总次数。

题目要求交换次数最少。

那么就是求 

k*(k-1)/2+

(N-k)*(N-k-1)/2的最小值。

 

很容易根据公式,二次函数在极值时取N/2的时候。

ac代码

#include<stdio.h>
#include<string.h>
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		int k=n/2;
		printf("%d\n",(k*(k-1))/2+(n-k)*(n-k-1)/2);
	}
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值