Crazy tea party-1455

本文探讨了Crazy茶会中,n位参与者围绕桌子坐成一圈并快速调整位置,使其坐位逆序排列所需的最短时间。通过类比冒泡排序,文章详细解释了计算不同人数情况下所需时间的方法,包括偶数和奇数人数的特殊情况,并提供了实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Crazy tea party
Time Limit: 1000MS
Memory Limit: 10000K
Total Submissions: 7229
Accepted: 4914

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

解题思路:
类似冒泡程序:
如果所有人是线性排列,那我们的工作就是类似冒泡程序做的工作:1,2,3,4,5变为5,4,3,2,1 ,耗时n(n-1)/2
但是出现了环,也就是说1,2,3,4,5变为3,2,1,5,4也可满足条件  
我们可以把这个环等分成两个部分 ,每个部分看成是线性的,再把它们花的时间加起来.
当n是偶数时, 每份人数n/2 ,即 2*(n/2)*(n/2 -1)/2,即n/2*(n/2 - 1);
当n是奇数时,两份的人数分别是n/2和n/2+1,即(n/2)*(n/2 -1)/2 + (n/2 +1)*(n/2)/2;
注意n/2是取整,不能进行通分操作,会出现误差,引起结果不正确。

实现代码如下:

/***********************************************************************
    Copyright (c) 2015,wangzp
    All rights no reserved.
  
    Name: 《Crazy tea party》In PEKING UNIVERSITY ACM
    ID:   PROBLEM 1455
    问题简述:  N个人围成一圈,找出最快反着做需要调换座位的次数。
 
    Date: SEP 09, 2015 
 
***********************************************************************/
#include 

/*偶数个人*/
int fun_even(int n)
{
	return n/2*(n/2 - 1);
}
/*奇数个人*/
int fun_odd(int n)
{
	return (n/2)*(n/2 -1)/2 + (n/2 +1)*(n/2)/2;
}
int main(void)
{
	int m,a,result;
	scanf("%d",&m);
	while(m--)
	{
		scanf("%d",&a);
		if (a%2 == 0)
		{
			result = fun_even(a);
			printf("%d\n",result);
		} 
		else
		{
			result = fun_odd(a);
			printf("%d\n",result);
		}
	}
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值