关于排序
查看原帖
关于排序
677126
LINCE楼主2023/8/2 11:14

链式前向星,原先以u为第一关键字,从小到大,92,改为从大到小,AC,为什么?

#include<bits/stdc++.h>
using namespace std;
int n,m,cnt,t,h,du,dv,head[5001],k[5001],ans[5001];
bool v[5001];
struct edge{
	int next,to;
}e[10001];
struct node{
	int u,v;
}p[20001];
void read(int &x){
	x=0;
	char ch=cin.get();
	while(ch<'0'||ch>'9')ch=cin.get();
	while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+ch-48,ch=cin.get();
}//快读
void add(int x,int y){
	e[++cnt].next=head[x];
	e[cnt].to=y;
	head[x]=cnt;
}//连边
bool cmp(const node& x,const node& y){
	if(x.u>y.u)return 1;
		else if(x.u==y.u&&x.v>y.v)return 1;
		else return 0;
}//排序
void dfs_tree(int x,int fa){
	if(v[x])return;
	k[++t]=x,v[x]=1;
	for(int i(head[x]);i;i=e[i].next){
		int y=e[i].to;
		if(x==du&&y==dv)continue;
		if(x==dv&&y==du)continue;
		if(y!=fa)dfs_tree(y,x);
	}
}//深搜
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	read(n);
	read(m);
	for(int i(1);i<=m;i++){
		read(p[i].u);
		read(p[i].v);
		p[i+m].u=p[i].v,p[i+m].v=p[i].u;
	}
	sort(p+1,p+1+2*m,cmp);
	for(int i(1);i<=m*2;i++){
		add(p[i].u,p[i].v);
	}
	if(m==n-1){
		dfs_tree(1,0);
		for(int i(1);i<=n;i++){
			cout<<k[i]<<" ";
		}
	}
		else if(m==n){
			memset(ans,0x3f,sizeof(ans));
			for(int i=1;i<=m;i++){
				t=0,h=0,du=p[i].u,dv=p[i].v;
				memset(v,0,sizeof(v));
				dfs_tree(1,0);
				if(t==n){
					for(int j(1);j<=n;j++){
						if(ans[j]<k[j]){
							h=0;
							break;
						}
							else if(ans[j]>k[j]){
								h=1;
								break;
							}
					}
					if(h)memcpy(ans,k,sizeof(k));
				}
			}
			for(int i(1);i<=n;i++){
				cout<<ans[i]<<" ";
			}
		}
}
2023/8/2 11:14
加载中...