标签:codeforces 链表
可以把序列中一个数改变,使得序列中后一个数与前一个数差的绝对值之和最小
把与数x相邻的数加入G[x]的链表中(若这个数值也为x,则不加入) 那么改变了数x,则相当于只会影响到这个链表中的数
为了让x变化后的数 与这个链表中的数差值绝对值之和最小 取排序后的序列的中位数即可
//#pragma comment(linker, "/STACK:102400000,102400000") //HEAD #include <cstdio> #include <cstring> #include <vector> #include <iostream> #include <algorithm> #include <queue> #include <string> #include <set> #include <stack> #include <map> #include <cmath> #include <cstdlib> #include <list> using namespace std; //LOOP #define FE(i, a, b) for(int i = (a); i <= (b); ++i) #define FED(i, b, a) for(int i = (b); i>= (a); --i) #define REP(i, N) for(int i = 0; i < (N); ++i) #define CLR(A,value) memset(A,value,sizeof(A)) //STL #define PB push_back //INPUT #define RI(n) scanf("%d", &n) #define RII(n, m) scanf("%d%d", &n, &m) #define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k) #define RS(s) scanf("%s", s) #define FF(i, a, b) for(int i = (a); i < (b); ++i) #define FD(i, b, a) for(int i = (b) - 1; i >= (a); --i) #define CPY(a, b) memcpy(a, b, sizeof(a)) #define FC(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++) #define EQ(a, b) (fabs((a) - (b)) <= 1e-10) #define ALL(c) (c).begin(), (c).end() #define SZ(V) (int)V.size() #define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p) #define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q) #define WI(n) printf("%d\n", n) #define WS(s) printf("%s\n", s) #define sqr(x) x * x typedef vector <int> VI; typedef unsigned long long ULL; typedef long long LL; const int INF = 0x3f3f3f3f; const int maxn = 100010; const double eps = 1e-10; const LL MOD = 1e9 + 9; int a[maxn]; VI G[maxn]; int main() { int n, m; while (~RII(n, m)) { REP(i, n + 1) G[i].clear(); FE(i, 1, m) RI(a[i]); LL tot = 0; FE(i, 1, m) { if (i != 1 && a[i] != a[i - 1]) G[a[i]].push_back(a[i - 1]); if (i != m && a[i] != a[i + 1]) G[a[i]].push_back(a[i + 1]), tot += abs(a[i + 1] - a[i]); } LL ans = tot; // cout << tot << "----" <<endl; FE(i, 1, n) { if (G[i].size() == 0) continue; LL t = tot; // cout << t1 << " ----x:"; sort(G[i].begin(), G[i].end()); int x = G[i][G[i].size() / 2]; REP(j, G[i].size()) t += abs(G[i][j] - x) - abs(G[i][j] - i); ans = min(ans, t); // cout << x <<" t2: " << t2 <<endl; } // if (m == 1) ans = 0; cout << ans << endl; } return 0; } /* 4 6 1 2 3 4 3 2 10 5 9 4 3 8 8 1000 5 0 1 1000 999 1 */
codeforces248(div1) A. Ryouko's Memory Note,布布扣,bubuko.com
codeforces248(div1) A. Ryouko's Memory Note
标签:codeforces 链表
原文地址:http://blog.csdn.net/colin_27/article/details/37907129