Luogu P2210 Haywire 题解

其实这题吧。。。有一种玄学解法

这题的要求的就是一个最小化的顺序

那么,我们就不进想到了一种显然的写法

就是random_shuffle

什么?这不是乱搞的非正解吗

然而,正如一句话说的好

一个算法,如果你无法将他卡到错误,那么他就是对的

所以,就产生了下面的科学随机写法

随机化顺序,模拟过程,取ans最小值

code

#include<bits/stdc++.h>

using namespace std;
const int MAXN=20;
void file(string s){freopen((s+".in").c_str(),"r",stdin);freopen((s+".out").c_str(),"w",stdout);}
int read()
{
    int f=1,a=0;char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-'){
            f=-f;
        }
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        a=a*10+ch-'0';
        ch=getchar();
    }
    return a*f;
}
int n,ans=0x3f3f3f3f;
int a[MAXN],fri[MAXN][MAXN];
int main()
{
//  file("");
    n=read();
    for(int i=1;i<=n;++i){
        int x=read(),y=read(),z=read();
        fri[i][x]=fri[i][y]=fri[i][z]=1;
        a[i]=i;
    }
    for(int i=1;i<=300000;++i){
        random_shuffle(a+1,a+n+1);
        int re=0;
        for(int j=1;j<=n;++j){
            for(int k=j+1;k<=n;++k){
                int pos1,pos2;
                if(!fri[j][k]){
                    continue;
                }
                for(int l=1;l<=n;++l){
                    if(a[l]==j){
                        pos1=l;
                    }
                    if(a[l]==k){
                        pos2=l;
                    }
                }
                re+=abs(pos1-pos2);
            }
        }
        ans=min(ans,re);
    }
    cout<<ans<<endl;
    return 0;
}

教给我这一写法的lbn @expect 太强了orzorz

推荐一道也可以这样科学解决随机化乱搞的题目:

P3959 宝藏

本文同步发于我的Luogu博客,欢迎各位大佬来碾压本蒟蒻

猜你喜欢

转载自www.cnblogs.com/zhu-chen/p/11823218.html