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;
}