P1878 舞蹈课
题解
1.朴素想法:链表存储+每次遍历一遍找出最小对
缺点:时间复杂度过高
改进措施:每次遍历一遍,只会挑走一对,剩下的会重复遍历,所以我们把所有的对都找出来放进堆里,每次挑出第一个没有被用到过的对
注意审题
code
#include<bits/stdc++.h>
using namespace std;
struct node
{
int x,y,d;
bool operator<(const node &b)const
{
if(b.d!=d)return b.d<d;
else return b.x<x;
}
};
struct name
{
int x,y;
};
int vis[200005]={0},a[200005],l[200005],r[200005];
vector<name> ans;
int main()
{
int n;
cin>>n;
string s;
cin>>s;
s=' '+s;
for(int i=1;i<=n;i++) cin>>a[i];
priority_queue<node> q;
for(int i=1;i<n;i++)
{
if(s[i]!=s[i+1])
{
q.push({i,i+1,abs(a[i]-a[i+1])});
}
l[i]=i-1;
r[i]=i+1;
}
l[n]=n-1;
r[n]=0;
while(q.size())
{
int x=q.top().x,y=q.top().y;
q.pop();
if(vis[x]||vis[y]) continue;
vis[x]=1;
vis[y]=1;
if(l[x]&&r[y]&&s[l[x]]!=s[r[y]])
q.push({l[x],r[y],abs(a[l[x]]-a[r[y]])});
ans.push_back({x,y});
if(l[x]) r[l[x]]=r[y];
if(r[y]) l[r[y]]=l[x];
}
cout<<ans.size()<<endl;
for(auto it:ans)
cout<<it.x<<" "<<it.y<<endl;
return 0;
}

浙公网安备 33010602011771号