## CSDN博客

### 习题 51：逆序数★

/*

1的前面有1个数比它要大，4的前面有1个数比它大，
3的前面有2个数比它大，总数是1+1+2=4

5
21543
3
123
6
654321
4
acdb
6
abcABC
4
2211

4
0
15
2
9
4

*/

#include <iostream>
using namespace std;
int main(void)
{
long long result;
long ascii[256];
int i, j, preCount;
//char max, min;
unsigned char cTmp = 0, preChar;
int n = 0;
while(EOF!=scanf("%d",&n))
{
result = 0;
memset(ascii, 0, 256*sizeof(long));
i = n - 1;
getchar();//'/n'
cTmp = getchar();//first char
preCount = 0;
preChar = cTmp;
while(i-- >= 0)
{
if(cTmp < preChar)
{
for(j = preChar; j > cTmp; j--)
{
preCount += ascii[j];
}
}else if( cTmp > preChar)
{
for(j = preChar; ++j <= cTmp;)
{
preCount -= ascii[j];
}
}
preChar = cTmp;
ascii[cTmp]++;
result += preCount;
cTmp= getchar();
}
//printf("%lld/n",result);//这种打印会出错，64位的不能正确打印
cout << result << endl;
}
return 0;
}
/*result:
Name: "younthu" Problem ID "51"Submit Time: 2008/9/28-10:02G++: Compile OKTest  1:    Accepted    Time = 0 msTest  2:    Accepted    Time = 0 msTest  3:    Accepted    Time = 0 msTest  4:    Accepted    Time = 0 msTest  5:    Accepted    Time = 313 ms--------------------------------Problem ID     51Test Result    AcceptedTotal Time     313 msTotal Memory   192 Kb / 1000 KbCode Length    1028 Bytes
*/

0 0