# 【luogu P5022 旅行】 题解

$NOIP2018 DAY2T1$

60分code：

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 5010;
struct edge{
int to, next;
}e[maxn<<2];
bool vis[maxn];
{
}
void dfs(int x)
{
if(vis[x]) return;
vis[x] = 1;
printf("%d ",x);
int a[maxn], num = 0;
for(int i = 1; i <= n; i++) a[i] = 0;
for(int i = head[x]; i != -1; i = e[i].next)
a[++num] = e[i].to;
sort(a+1, a+1+num);
for(int i = 1; i <= num; i++)
dfs(a[i]);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1; i <= m; i++)
{
int u, v;
scanf("%d%d",&u,&v);
}
dfs(1);
return 0;
}


100分做法：

code：

#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 5010;
struct edge{
int to, next;
}e[maxn<<2];
int head[maxn], cnt, n, m, u[maxn], v[maxn];
bool vis[maxn];
{
}
void dfs(int x)
{
if(vis[x]) return;
vis[x] = 1;
printf("%d ",x);
int a[maxn], num = 0;
for(int i = 1; i <= n; i++) a[i] = 0;
for(int i = head[x]; i != -1; i = e[i].next)
a[++num] = e[i].to;
sort(a+1, a+1+num);
for(int i = 1; i <= num; i++)
dfs(a[i]);
}
//=======================
vector<int> E[maxn];
int ANS[maxn], NOW[maxn], TOT, CUTu, CUTv;
bool VIS[maxn];
void DFS(int x)
{
if(VIS[x]) return;
VIS[x] = 1;
NOW[++TOT] = x;
for(int i = 0; i < E[x].size(); i++)
{
int y = E[x][i];
if((y == CUTv && x == CUTu) || (x == CUTv && y == CUTu)) continue;
DFS(y);
}
}
bool check()
{
for(int i = 1; i <= n; i++)
{
if(ANS[i] == NOW[i]) continue;
if(ANS[i] > NOW[i]) return 1;
if(ANS[i] < NOW[i]) return 0;
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1; i <= m; i++)
{
scanf("%d%d",&u[i],&v[i]);
E[u[i]].push_back(v[i]);
E[v[i]].push_back(u[i]);
}
for(int i = 1; i <= n; i++) sort(E[i].begin(), E[i].end());
if(m == n-1)
{
dfs(1);
return 0;
}
else
{
for(int i = 1; i <= m; i++)
{
TOT = 0, CUTu = u[i], CUTv = v[i];
memset(VIS, 0, sizeof(VIS));
DFS(1);
if(TOT == n)
{
if(ANS[1] == 0)
{
for(int j = 1; j <= n; j++)
ANS[j] = NOW[j];
}
else if(check())
{
for(int j = 1; j <= n; j++)
ANS[j] = NOW[j];
}
}
}
for(int i = 1; i <= n; i++)
printf("%d ",ANS[i]);
return 0;
}
}


DAY2考时想不起环套树来，考后出考场的一刹那就想到了可以N^2暴力断边。

posted @ 2019-06-11 11:20  Misaka_Azusa  阅读(202)  评论(0编辑  收藏
Live2D