微软2014在线笔试 第三题

Description

Find a pair in an integer array that swapping them would maximally decrease the inversion count of the array. If such a pair exists, return the new inversion count; otherwise returns the original inversion count.

Definition of Inversion: Let (A[0], A[1] ... A[n]) be a sequence of n numbers. If i < j and A[i] > A[j], then the pair (i, j) is called inversion of A.

Input
Input consists of multiple cases, one case per line.Each case consists of a sequence of integers separated by comma.

Output
For each case, print exactly one line with the new inversion count or the original inversion count if it cannot be reduced.

#include <stdio.h>
#include <string.h>

#define MAXWORDS 100

int main()
{
	char c;
	int i, j, num, ans, time;
	char cc[MAXWORDS];

	memset(cc, '*', sizeof(cc));

	printf("INPUT THE time YOU WANT \n");
	scanf("%d", &time);

	setbuf(stdin,NULL);
	while(time--)
	{
		printf("INPUT THE COUNT ARRAY YOU WANT \n");
		i = 0;
		num = 0;
		while((c = getchar())!= '\n')
		{
			if (c != ',')
			{
				cc[i] = c;
				i++;
				num++;
			}
		}

		ans = 0;
		for (i = 0; i < num - 1; i++)
		{
			for (j = i + 1; j < num; j++)
			{
				if (cc[i] > cc[j])
				{
					ans++;
				}
			}
		}
		printf(" THE ANSWER IS %d\n", ans);
	}
	return 0;
}



心得:算法遍历了整个数组,利用了两个循环:

for (i = 0; i < num - 1; i++)
	{
		for (j = i + 1; j < num; j++)
		{

在数组排序的时候也用到这两的循环,i from0 to num-1;j from i+1 to num。这样,j永远大于i,我们只需要判断cc[i] > cc[j]即可。


关于函数setbuf(stdin,NULL)——

在第一次完成函数之前没有加这个语句。所以输入完测试例的数目time,习惯性按下回车,这样导致第一次循环的时候,c直接被赋值为'\n',然后进入下一个循环。通过函数setbuf(stdin,NULL)清空输入流中的缓存,在这里就是你多余输入的那个'\n',然后重新输入c。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值