PAT甲级_1067 Sort with Swap(0, i) (25 分)|1037 Magic Coupon (25 分)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44705116/article/details/102558705

1、1067 Sort with Swap(0, i) (25 分)、

题目大意:给出一个乱序数列,只使用swap(0,x),得到最少交换次数;

很容易超时。

先给出一份超时代码:

 #include<iostream>
#include<vector>
#include<cstdio>
using namespace std;

int main() {
	int n;
	scanf_s("%d", &n);
	int num;
	vector<int> oh(n+10);
	for (int i = 0; i < n; i++) {
		scanf_s("%d", &num);
		oh[num] = i;
	}
	int count = 0, index = 1;
	while (true) {
		if (oh[0] == 0) {
			while (oh[index] == index) {
				index++;
				if (index == n - 1) break;
			}
			if (index == n - 1) break;
			swap(oh[0], oh[index]);
			count++;
		}
		while (oh[0] != 0) {
			swap(oh[oh[0]], oh[0]);
			count++;
		}
	}
	printf("%d", count);
	return 0;
}

为解决超时,在存入数据的同时,统计需要变化的数量,以数量为while结束的依据。

使用贪心算法,0不在第零位时将0于本应在0位置的数交换,0在第零位时找出不该在当时位置上的最早的数与0交换;

#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;

int main() {
	int n;
	scanf_s("%d", &n);
	int num;
	vector<int> oh(n+10);
	int cns=0;
	for (int i = 0; i < n; i++) {
		scanf_s("%d", &num);
		oh[num] = i;
		if (num != i&&num!=0) cns++;
	}
	int count = 0, index = 1;
	while (cns>0) {
		if (oh[0] == 0)
		{
			while (index < n) {
				if ( oh[index]!=index) {
					count++;
					swap(oh[0], oh[index]);
					break;
				}
				index++;
			}
		}
		while (oh[0] != 0) {
			swap(oh[oh[0]], oh[0]);
			count++;
			cns--;
		}
	}
	printf("%d", count);
	return 0;
}


为避免超时,每次找最早不配位的数时不从头遍历,定义一index,从1开始,将不配位的数按序替换;

2、1037 Magic Coupon (25 分)

题目大意:给出两个数列,得到其元素之积的最大和。

使用贪心算法,在两数都负,都正时从末端取值求积。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
    int m, n;
    scanf("%d", &m);
    vector<int> cou(m);
    for(int i=0;i<m;i++){
        scanf("%d", &cou[i]);
    }
    scanf("%d", &n);
    vector<int> pro(n);
    for(int i=0;i<n;i++){
        scanf("%d", &pro[i]);
    }
    sort(cou.begin(), cou.end());
    sort(pro.begin(), pro.end());
    int q=0, p=0, ans=0;
    while(q<m&&p<n&&cou[q]<0&&pro[p]<0){
        ans+=cou[q]*pro[p];
        q++;
        p++;
    }
    q=m-1;
    p=n-1;
     while(q>=0&&p>=0&&cou[q]>0&&pro[p]>0){
        ans+=cou[q]*pro[p];
        q--;
        p--;
    }
    printf("%d", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44705116/article/details/102558705
今日推荐