Codeforces Round #659 (Div. 1) A (并查集,拓扑排序,优先队列)

https://codeforces.com/problemset/problem/1383/A
在这里插入图片描述
在这里插入图片描述

  1. 并查集 :https://blog.csdn.net/jziwjxjd/article/details/107603759
  2. 拓扑排序 :https://blog.csdn.net/weixin_45817880/article/details/107573083
  3. 优先队列 :
#include<bits/stdc++.h>
#define ios std::ios::sync_with_stdio(false) 
#define rep(i,a,n) for (int i=a;i<=n;i++)
using namespace std;

const int N = 2e5 + 10;
int T,n,ans;
char s1[N],s2[N];
struct node{
	char c;
	int w;
	bool operator<(const node& A)const{
		if (c == A.c) return w > A.w;
		else return c > A.c;
	}
};
int main()
{
	cin >> T;
	while (T--){
		priority_queue<node>q;
		ans = 0;
		cin >> n;
		cin >> s1 >> s2;
		int flag = 0;
		rep(i,0,n-1){
			if (s1[i] < s2[i]){
				q.push({s1[i],s2[i]-s1[i]});	
			}
			else if (s1[i] > s2[i]){
				cout << "-1\n";
				flag = 1;
				break;
			} 
		}
		if (flag) continue;
		while(!q.empty()){
			node tmp = q.top();
			q.pop();
			while (!q.empty() && tmp.c == q.top().c && tmp.w == q.top().w) q.pop();
			if (q.empty()||tmp.c != q.top().c) ans++;
			else{
				while(!q.empty()&&tmp.c == q.top().c){
					q.push({(char)(tmp.c+tmp.w),q.top().w-tmp.w});
					q.pop();
				}
				ans++;
			} 
		}
		cout << ans << "\n";
	}
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值