POJ-1455(换位置)(Crazy tea party )

【题目描述】

围着桌子坐着n个人,现在要将每个人左右的人交换一下,最少交换多少次?

【解题思路】

如果奇数个人,找一个基准点

如果偶数个人,找两个基准点(注意特殊处理除了基准点还有奇数对数的情况,详见代码)

int main()
{
	int cases;
	cin>>cases;
	while (cases--) {
		int x;
		cin>>x;
		if (x <= 2) printf("0\n");
		else if (x == 3) printf("1\n");
		else if (x == 4) printf("2\n");
		else {
			if (x % 2 == 0) {
				int now = x - 2;
				now /= 2;
				int y = now / 2;
				int i, sum = 0, times = 3;
				for (i = 0; i < y; ++i) {
					sum += times;
					times += 4;
				}
				sum *= 2;
				if (now % 2 != 0) {
					sum += times;
				}
				if (now % 2 == 1) --sum;//特殊处理,就那8来说,除了两个上下两个基准点,
				//首先移动最中间那一对,这一对移回来的时候,可以把上一对先移动一个,这样就减少了1
				printf("%d\n", sum);
			} else {
				int now = x - 1;
				now /= 2;
				int y = now / 2;
				int i, sum = 0, times = 3;
				for (i = 0; i < y; ++i) {
					sum += times;
					times += 4;
				}
				times = 1;
				for (i = 0; i < y; ++i) {
					sum += times;
					times += 4;
				}
				if (now % 2 != 0) {
					sum += times;
				}
				printf("%d\n", sum);
			}
		}
	}
    return 0;
}



你可能感兴趣的:(POJ-1455(换位置)(Crazy tea party ))