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