【JZOJ 4310】【NOIP2015模擬11.4】最優交換(貪心)

問題描述
這裏寫圖片描述
輸入
這裏寫圖片描述
輸出
這裏寫圖片描述
樣例輸入
2
1432 2
4321 2
樣例輸出
4312
4321
這裏寫圖片描述
算法討論
用貪心就能過了,在當前位置以後,長度爲k的子串中找到最大的交換即可。

#include <cstdio>
using namespace std;
long long a[56],t,k,maxx,p;
bool f;

int main()
{
    freopen("swap.in","r",stdin);
    freopen("swap.out","w",stdout);
    scanf("%lld",&t);
    while (t>0)
    {
        long long x,n=0;
        scanf("%d%d",&x,&k);
        while (x>0)
        {
            a[++n]=x % 10;
            x/=10;
        }
        for (int i=n;i>=1;i--)
        {
            maxx=a[i]; f=0; a[0]=0;
            int tt=i-k;
            if (tt<1)
                tt=1;
            for (int j=i-1;j>=tt;j--)
                if (a[j]>maxx)
                {
                    maxx=a[j];
                    p=j;
                    f=1;
                }
            if (f)
            {
                k-=(i-p);
                a[0]=a[p];
                for (int j=p;j<i;j++)
                    a[j]=a[j+1];
                a[i]=a[0];
                if (k==0) 
                    break;
            }
        }
        for (int i=n;i>=1;i--)
            printf("%lld",a[i]);
        printf("\n");
        t--;
    }
    fclose(stdin); fclose(stdout);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章