LA5904 Please, go first

来源:互联网 发布:小学英语课文朗读软件 编辑:程序博客网 时间:2024/05/25 23:57

题目地址: LA5904

题目大意    现在有一个序列  例如 AABBCCB

同一类字母代表同一批人,用只能载一个人电梯载他们上山顶滑雪,同一批人要一起出发,所以先上去的人如果还有成员没有到齐还是得等。

现在问怎样能使在不让任何一个人等待时间变长的基础下,使得总的节省时间最短(每个人节省的时间的和)


算法是:根据每一类的最后一名出现的顺序排序。

实现:扫一遍  用map存储


证明: 实际上 每一批人的最后一名的相对顺序没有改变,只是同一类人集中了,那么这样倒着看,只可能最后一名的绝对位置前移(或不动)了,满足了交换时不会让等到时间变长。

最后变成AABBCC这样的形式  不能继续优化了

代码:

#include<iostream>#include<algorithm>#include<map>#include<cmath>using namespace std;char p[25005];map<char,int>   themap,newmap;int  cmp(char a,char b){    if(themap[a]<themap[b])  return 1;    else return 0;}int main(){    int cas;    cin>>cas;    int n;    while(cas--)    {        themap.clear();        newmap.clear();        cin>>n;        char ch;        for(int i=0;i<n;i++)        {            cin>>ch;            p[i]=ch;            themap[ch]=i;        }                sort(p,p+n,cmp);                for(int i=0;i<n;i++)        {             newmap[p[i]]=i;        }        int ans=0;        for(int i=0;i<n;i++)        {            ans+=abs(themap[p[i]]-newmap[p[i]]);        }        ans*=5;        cout<<ans<<endl;                    }}



0 0