神の构造!
考虑最短的哈密顿路径一定是经过了不重不漏 个点,所以长度肯定为 。
现在加入我们加入了 个点 ,现在要加入的点为 ,有两种情况:
-
加入的 条边的颜色相同,那么我们可以直接将使 ,可以证明这样无影响。
-
加入的 条边已经在 使用了一张车票,那么我们要考虑在 进行分类讨论。
-
若 的路径与左半边颜色相同,则我们可以把 插入到 后面。由于 的路径颜色与 的颜色相同,所以无论 是什么颜色,都可以满足条件。
-
否则我们把 插入在 的前面。证明同上。
-
我们发现我们需要一个数据结构,维护可在任意位置插入,所以可以用链表。
但是,我们还可以考虑维护两个双端队列,分别表示每种颜色的纯色边。然后模拟即可,具体细节看代码。
#include<iostream>
#include<algorithm>
#include<queue>
const int sz=2010;
int f[sz][sz],n;
int next(int x){
if(x==n)return 1;
return x+1;
}
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cin>>n;
for(int i=2;i<=n;i++){
for(int j=1;j<i;j++){
char ch;
std::cin>>ch;
f[i][j]=f[j][i]=ch=='R';
}
}
for(int i=1;i<=n;i++){
std::deque<int>l,r;
l.push_back(i),l.push_back(next(i));
int cur=next(next(i)),col=f[i][next(i)];
while(cur!=i){
if(r.empty()){
if(f[l.back()][cur]==col)l.push_back(cur);
else r.push_front(cur);
}else{
if(f[l.back()][cur]==col){
l.push_back(cur);
if(f[l.back()][r.front()]==col)
l.push_back(r.front()),r.pop_front();
}else{
r.push_front(l.back()),l.pop_back();
if(f[l.back()][cur]==col)l.push_back(cur);
else r.push_front(cur);
}
}
if(l.size()==1)l.swap(r),r.clear(),l.push_front(i),col^=1;
cur=next(cur);
}
std::cout<<n<<"\n";
while(!l.empty())std::cout<<l.front()<<" ",l.pop_front();
while(!r.empty())std::cout<<r.front()<<" ",r.pop_front();
std::cout<<"\n";
}
return 0;
}后记:其实这题的难度在于如何想明白插入删除的过程,想要完成代码并不是很难。(这应该也是常规构造题的特点了吧)