#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //#define int long long #define rep(i,s,n) for(int i = s;i=(s);i--) #define all(v) (v).begin(),(v).end() #define pb push_back #define fi first #define se second #define chmin(a,b) a=min((a),(b)) #define chmax(a,b) a=max((a),(b)) typedef long long ll; typedef pairpint; typedef vectorvint; typedef vectorvpint; typedef pair P1; typedef pair P2; typedef pair PP; static const ll maxLL = (ll)1 << 62; const ll MOD = 1000000007; const ll INF = 1e18; int ca[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; int n, m, minn = 99999999; vectorlist; struct MyStruct { bool flag[1005]; }; int func1(int index, int cnt, int sum) { if (cnt == n) { minn = min(minn, sum); return 0; } if (index < 1) { func1(index + 1, cnt + 1, sum + abs(list[index] - list[index + 1])); } else { if (abs(list[index] - list[index - 1]) < abs(list[index] - list[index + 1])) { func1(index - 1, cnt + 1, sum + abs(list[index] - list[index - 1])); } else if (abs(list[index] - list[index - 1]) > abs(list[index] - list[index + 1])) { func1(index + 1, cnt + 1, sum + abs(list[index] - list[index + 1])); } else if (abs(list[index] - list[index - 1]) == abs(list[index] - list[index + 1])) { func1(index - 1, cnt + 1, sum + abs(list[index] - list[index - 1])); func1(index + 1, cnt + 1, sum + abs(list[index] - list[index + 1])); } } return 0; } int func2(int index, int cnt, int sum, MyStruct st) { if (sum >= minn) { return 0; } if (cnt == n) { minn = min(minn, sum); return 0; } for (int i = 0; i < m; i++) { if (st.flag[i] == false) { st.flag[i] = true; func2(i, cnt + 1, sum + abs(list[index] - list[i]), st); } } return 0; } signed main() { int i, j; int index; MyStruct st; memset(st.flag, 0, sizeof(st.flag)); cin >> n >> m; for (i = 0; i < m; i++) { int num; cin >> num; list.push_back(num); } sort(list.begin(), list.end()); for (i = 0; i < m; i++) { if (minn > abs(0 - list[i])) { index = i; minn = abs(list[i]); } } minn = 99999999; func1(index, 1, abs(list[index])); for (i = 0; i < m; i++) { st.flag[i] = true; func2(i, 1, abs(list[i]), st); st.flag[i] = false; } cout << minn << endl; getchar(); getchar(); return 0; }