Codeforces Round #560 (Div. 3) D. Almost All Divisors、C. Good String题解

D. Almost All Divisors

Codeforces Round #560 (Div. 3) D. Almost All Divisors、C. Good String题解_第1张图片

       题意:给出t组测试数据,每组测试数据给出n个数,这n个数是guessed number除去本身和1以外的所有因子,输出最小的guessed number。

       思路:sort排序所有因子di,将最小的因子和最大的因子相乘,得到的既是所有guessed number(假定此数满足题意),此时再将得到的数求出所有除本身与1之外的所有因子,与题目给出的所有因子相比较,只要因子相同,则此数满足题意,输出,不同则输出-1。

       数据范围:1 <= n <= 300,2 <= di <= 1e6。

       时间复杂度:O(n) + log(n)

       只有我不知道的小技巧(?):用vector可以直接比较元素,不用像数组那样一个一个比较。

       AC代码:

#include
using namespace std;

int main(){
	int t;
	cin >> t;
	while(t--){
		int n;
		cin >> n;
		vector a, b;
		for(int i = 1; i <= n; i++){
			int c;
			cin >> c;
			a.push_back(c);
		}
		sort(a.begin(), a.end());
		long long x = 1ll * a[0] * a[n - 1];
		int now = 0;
		for(int i = 2; i <= sqrt(x); i++){
			if(x % i == 0){
				b.push_back(i);
				if(x / i != i) b.push_back(x / i);
			}
		}
		sort(b.begin(), b.end());
		if(a == b) cout << x << endl;
		else cout << "-1" << endl;
	}
	return 0;
}

 C. GoodString

Codeforces Round #560 (Div. 3) D. Almost All Divisors、C. Good String题解_第2张图片

        题意:给出长度为n的字符串,要求使字符串变成定义为good的字符串,good字符串定义为:字符串长度为偶数,且奇数位置上的字符与下一个字符不相同,特别地定义长度为0的字符串也为good字符串。输出需要删减的字符个数以及删减完后最终的字符串,要求删除的字符个数最少。

        思路: 易发现当答案字符串的长度为偶数时可以直接将当前遍历到的字符直接加入,当答案字符串长度为奇数时如果当前遍历到的字符与答案字符串中的最后一个字符一样就不加入,反之则加入。最终判断一下答案字符串的长度是否为奇数,如果是奇数就把最后一个字符删除。

        时间复杂度:O(n)

        涉及算法:贪心。

        AC代码: 

#include
#include
#include
#include
using namespace std;

int main(){
	int n;
	string s, ans;
	cin >> n >> s;
	for(int i = 0; i < n; i++){
		if(ans.size() & 1){
			if(s[i] != ans[ans.size() - 1]){
				ans += s[i];
			}
		}
		else ans += s[i];
	}
	if(ans.size() & 1) ans.erase(ans.size() - 1, 1);
	cout << n - ans.size() << endl << ans << endl;
	return 0;
}

 

你可能感兴趣的:(题解)