您的位置:首页 > 其它

Codeforces Round #324 (Div. 2) E. Anton and Ira(贪心)

2016-01-28 19:11 357 查看
题意:

给定N≤2000的两个序列,通过交换第一个序列变成第二个序列

如果交换ai和aj,交换的代码为|i−j|,给出交换代价最小的一个构造方案

分析:

显然对于每次交换,交换的双方必然向着它们该去的方向交换是最优的,显然这样交换是正确方案之一

发现这个之后如何构造一个解



考虑从右往左构造,如果1要到2,直接换过去显然是可以的

但是中途我们发现3,4要去1那边,显然我们将1和3,4交换,达成了共赢

这样就构造出了一个交换方案了

代码:

//
//  Created by TaoSama on 2016-01-28
//  Copyright (c) 2015 TaoSama. All rights reserved.
//
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>

using namespace std;
#define pr(x) cout << #x << " = " << x << "  "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;

int n, a
, b
;
int to
;

int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
//  freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);

while(scanf("%d", &n) == 1) {
for(int i = 1; i <= n; ++i) scanf("%d", a + i);
for(int i = 1; i <= n; ++i) scanf("%d", b + i);
for(int i = 1; i <= n; ++i) to[b[i]] = i;

int ans = 0;
vector<pair<int, int> > path;
for(int i = n; i; --i) {
int pos = i;
for(int j = i + 1; j <= to[a[pos]]; ++j) {
if(to[a[j]] <= pos) {
ans += abs(pos - j);
path.push_back({pos, j});
swap(a[pos], a[j]);
pos = j;
}
}
}
printf("%d\n%d\n", ans, path.size());
for(auto p : path) printf("%d %d\n", p.first, p.second);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  贪心