习题 51:逆序数★

 /*

问题描述
在线性代数里有这么一个概念:有一个数列,如21543,
1的前面有1个数比它要大,4的前面有1个数比它大,
3的前面有2个数比它大,总数是1+1+2=4
所以21543的逆序数就是4

输入
多组测试数据,第一行是n(1<=n<=1e7),下一行是一个长度为n的字符串

输出
算出这个字符串的逆序数(ASCII比较)

样例输入
5
21543
3
123
6
654321
4
acdb
6
abcABC
4
2211

样例输出
4
0
15
2
9
4

难度:Very Easy


*/

#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:02

G++: Compile OK

Test  1:    Accepted    Time = 0 ms
Test  2:    Accepted    Time = 0 ms
Test  3:    Accepted    Time = 0 ms
Test  4:    Accepted    Time = 0 ms
Test  5:    Accepted    Time = 313 ms
--------------------------------
Problem ID     51
Test Result    Accepted
Total Time     313 ms
Total Memory   192 Kb / 1000 Kb
Code Length    1028 Bytes
*/
<script>sh_highlightElement(document,code0);</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值