跳到正文

题解

P17004 题解

ikunTLE约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年7月9日
收录
2026年7月14日
更新
2026年11月8日
篇幅
约 4 分钟
获赞
1
题目
P17004

版本

  1. v1当前

思路

提供一个扔掉大脑的纯模拟的做法。

首先用并查集判断所有人之间是否联通,若不连通直接输出 impossible 即可。

然后将所有人和连接他们的数字全部建成图。由于数的值域到了 10910^9,需要将它们离散化。

注意到建完的图是一个二分图,因为所有人都连向数,所有数都连向人。我们便可以用 bfs 遍历,贪心地输出每一条边。

AC CODE

C++
#include<bits/stdc++.h>
using namespace std;
int read(){int x=0;char f=1,ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}
const int N=2e5+10;
struct node{
	int val,id;
};vector<node>vc[N*2];
struct Node{
	int u,last;
};queue<Node>q;
int fa[N*2];
bool flag[N],vis[N*2];
void _init(){
	for(int i=0;i<N*2;++i)
		fa[i]=i;
	return;
}
int _find(int x){
	if(x==fa[x])
		return x;
	fa[x]=_find(fa[x]);
	return fa[x];
}
void _merge(int x,int y){
	int xx=_find(x),yy=_find(y);
	if(xx<yy)
		swap(xx,yy);
	if(xx!=yy)
		fa[xx]=yy;
	return;
}
int main(){
	_init();
	int n=read();
	vector<int>val;
	for(int i=1;i<=n;++i){
		int m=read();
		while(m--){
			int x=read();
			vc[i].push_back({x,0});
			val.push_back(x);
		}
	}
	val.push_back(0);
	sort(val.begin(),val.end());
	val.erase(unique(val.begin(),val.end()),val.end());
	for(int i=1;i<=n;++i)
		for(auto&[v,id]:vc[i]){
			id=lower_bound(val.begin(),val.end(),v)-val.begin();
			_merge(i,id+n);
		}
	for(int i=1;i<=n;++i)
		flag[_find(i)]=true;
	int cnt=0;
	for(int i=1;i<=n;++i)
		cnt+=flag[i];
	if(cnt>=2)
		return printf("impossible\n"),0;
	for(int i=1;i<=n;++i)
		for(auto[_,id]:vc[i])
			vc[id+n].push_back({0,i});
	vis[1]=true;
	for(auto[_,id]:vc[1])
		q.push({id+n,1}),vis[id+n]=true;
	while(!q.empty()){
		auto[u,last]=q.front();q.pop();
		for(auto[_,p]:vc[u])
			if(!vis[p]){
				vis[p]=true;
				printf("%d %d %d\n",last,p,val[u-n]);
				for(auto[__,v]:vc[p])
					if(!vis[v+n])
						q.push({v+n,p}),vis[v+n]=true;
			}
	}
	return 0;
}
原文
存档评论1 条抓取于