Codeforces Round #541 (Div. 2) F. Asya And Kittens//优先队列+bfs()||并查集+链表
题意就是上面那个图,已知数组size和合并路径,求初始的数组(不唯一)。
做法1
一开始想要并查集,但是不会记录路径,就换了一种想法,(过了!!!)
输入的n-1条边,对于第i条边,赋予权值i,建立无向图,
用类似prim算法的思想,每次加入能从集合到补集的权值最小的边对应的点。
加入的顺序就是答案。
为什么这样做的是对的:
每次加入都是权值小的边连到的点,那么说明该点优先级高,也就是在更小的集合里,所以输出改点,而一个集合里的顺序在是不重要的,所以可以保证正确。
#include<bits/stdc++.h>
using namespace std;
#define LL long long
struct no{int to,c;};
bool operator<(const no &x,const no &y){
return x.c>y.c;
}
vector<no>g[150005];
bool vis[150005];
priority_queue<no>q;
void bfs(no s){
while(!q.empty())q.pop();
q.push(s);
while(!q.empty()){
no now=q.top();
q.pop();
cout<<now.to<<' ';
for(int i=0;i<g[now.to].size();i++){
no x=g[now.to][i];
if(vis[x.to]==0){
vis[x.to]=1;
q.push(x);
}
}
}
}
int main(){
ios::sync_with_stdio(false);
int n;
cin>>n;
no st;
for(int i=1;i<n;i++){
int u,v;
cin>>u>>v;
if(i==1)st=(no){u,0}; //空集合加入起点
g[u].push_back((no){v,i});
g[v].push_back((no){u,i});
}
vis[st.to]=1;
bfs(st);
return 0;
}
做法2
好吧,这是常规做法,直接模拟并用并查集维护。
一开始是n个链表,最后合并成一个链表,不断跟新path。
对于输入一个x和y,
对于x所在的链表,他的左端点就是found(x),他的右端点就是last[fx],合并的时候(下图)维护这两个值就ok了。并记录path[i]=i的前驱。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 150005;
int pre[maxn];
int last[maxn];
int path[maxn];
int found(int x){
int re=x;
while(re!=pre[re]){
re=pre[re];
}
while(x!=pre[x]){
int j=pre[x];
pre[x]=re;
x=j;
}
return re;
}
int main(){
int n;cin>>n;
for(int i=1;i<=n;i++)pre[i]=i,last[i]=i;
for(int i=1;i<n;i++){
int x,y;cin>>x>>y;
int fx=found(x),fy=found(y);
path[fy]=last[fx];
pre[fy]=fx; //合并
last[fx]=last[fy]; //跟新右端点
}
for(int i=last[found(1)];i;i=path[i]) cout<<i <<' ';
return 0;
}