m=n-1的时候,就直接贪心地dfs就可以
m=n的话,就可以枚举删掉一条边,然后照着m=n-1做
$O(n^2)$大概能过
(然而我眼瞎看不到m<=n)
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<vector> 5 #include<queue> 6 #include<set> 7 using namespace std; 8 typedef long long ll; 9 typedef pair<int,int> pa; 10 const int maxn=5010; 11 12 inline ll rd(){ 13 ll x=0;char c=getchar();int neg=1; 14 while(c<'0'||c>'9'){ 15 if(c=='-') neg=-1; 16 c=getchar(); 17 }while(c>='0'&&c<='9') x=x*10+c-'0',c=getchar(); 18 return x*neg; 19 } 20 21 int N,M; 22 int eg[maxn*2][2],egh[maxn],ect=1; 23 int ans[maxn],del[2]; 24 25 inline void adeg(int a,int b){ 26 eg[++ect][0]=b,eg[ect][1]=egh[a];egh[a]=ect; 27 } 28 bool flag[maxn]; 29 bool dfs(int x,int f){ 30 ans[++ans[0]]=x;flag[x]=1; 31 for(int i=egh[x];i;i=eg[i][1]){ 32 int b=eg[i][0]; 33 if(b==f||(x==del[0]&&b==del[1])||(x==del[1]&&b==del[0])) continue; 34 if(flag[b]) return 1; 35 if(dfs(b,x)) return 1; 36 }return 0; 37 } 38 39 inline void solve1(){ 40 dfs(1,0); 41 for(int i=1;i<=N;i++) printf("%d ",ans[i]); 42 } 43 44 int lst[maxn]; 45 inline void solve2(){ 46 for(int i=1,j;i<=N;i++){ 47 del[0]=i; 48 for(int k=egh[i];k;k=eg[k][1]){ 49 del[1]=eg[k][0]; 50 memset(flag,0,sizeof(flag)); 51 ans[0]=0; 52 if(dfs(1,0)) continue; 53 if(ans[0]<N) continue; 54 bool b=1; 55 for(j=1;j<=N;j++){ 56 if(lst[j]==ans[j]) continue; 57 if(lst[j]&&lst[j]<ans[j]) b=0; 58 break; 59 } 60 if(b) memcpy(lst+j,ans+j,4*(N-j+1)); 61 } 62 63 } 64 for(int i=1;i<=N;i++) 65 printf("%d ",lst[i]); 66 } 67 68 int main(){ 69 // freopen("travel.in","r",stdin); 70 // freopen("travel.out","w",stdout); 71 int i,j,k; 72 N=rd(),M=rd(); 73 for(i=1;i<=M;i++){ 74 int a=rd(),b=rd(); 75 q[a].push(b),q[b].push(a); 76 } 77 for(i=1;i<=N;i++){ 78 while(!q[i].empty()){ 79 int p=q[i].top();q[i].pop(); 80 adeg(i,p); 81 } 82 } 83 if(M==N-1) solve1(); 84 else solve2(); 85 return 0; 86 }