Min Number 贪心,把最小的数放在最前

题目链接

Problem 2111 Min Number

Accept: 499    Submit: 949
Time Limit: 1000 mSec    Memory Limit : 32768 KB

Problem Description

Now you are given one non-negative integer n in 10-base notation, it will only contain digits ('0'-'9'). You are allowed to choose 2 integers i and j, such that: i!=j, 1≤i<j≤|n|, here |n| means the length of n’s 10-base notation. Then we can swap n[i] and n[j].

For example, n=9012, we choose i=1, j=3, then we swap n[1] and n[3], then we get 1092, which is smaller than the original n.

Now you are allowed to operate at most M times, so what is the smallest number you can get after the operation(s)?

Please note that in this problem, leading zero is not allowed!

Input

The first line of the input contains an integer T (T≤100), indicating the number of test cases.

Then T cases, for any case, only 2 integers n and M (0≤n<10^1000, 0≤M≤100) in a single line.

Output

For each test case, output the minimum number we can get after no more than M operations.

Sample Input

3
9012 0
9012 1
9012 2

Sample Output

9012
1092
1029 


每次操作可以换两个数位上的数

最多m次操作

问操作完可以得到的最小的数是多少


贪心,第一位不能是零,然后找最小的数 不断放在最前面的位数。

9012  首位不能是0 所以把其余最小的1 放在首位上 得 1092   ;第二位已经最小  所以把第三位9换成剩下的最小的2 得1029;





最小生成树问题可以使用贪心算法来解决,其中Prim算法和Kruskal算法是两种常见的贪心算法。 下面以Prim算法为例,给出C语言的实现: ```c #include <stdio.h> #include <stdbool.h> #define INFINITY 1000000 int n; // 顶点 int graph[100][100]; // 图的邻接矩阵 int lowcost[100]; // 存储当前点到已选点集的最小边权值 bool visited[100]; // 标记点是否已被选中 // Prim算法求最小生成树 void Prim(int v0) { int i, j, k; int min, sum = 0; // 初始化 for (i = 0; i < n; i++) { lowcost[i] = graph[v0][i]; visited[i] = false; } visited[v0] = true; // 每次找到一个未被选中的点集中到已选点集最小边 for (i = 1; i < n; i++) { min = INFINITY; k = v0; for (j = 0; j < n; j++) { if (!visited[j] && lowcost[j] < min) { min = lowcost[j]; k = j; } } visited[k] = true; sum += min; for (j = 0; j < n; j++) { if (!visited[j] && graph[k][j] < lowcost[j]) { lowcost[j] = graph[k][j]; } } } printf("The weight of the minimum spanning tree is: %d\n", sum); } int main() { int i, j, v0; // 输入图的顶点和邻接矩阵 printf("Please input the number of vertices: "); scanf("%d", &n); printf("Please input the adjacency matrix: \n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { scanf("%d", &graph[i][j]); } } // 输入起始点 printf("Please input the starting vertex: "); scanf("%d", &v0); // 求最小生成树 Prim(v0); return 0; } ``` 以上代码使用了邻接矩阵来表示图,时间复杂度为O(n^2)。如果使用邻接表来表示图,则时间复杂度可以优化到O(nlogn)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值