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交换,达成了共赢
这样就构造出了一个交换方案了
代码:
给定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; }
相关文章推荐
- 1.一些 贪心算法 的简单思维题:
- 贪心算法——字典序最小问题
- 贪心算法——区间调度问题
- Jump Game I,II 贪心
- Wildcard Matching
- 贪心法实现无向图的划分 代码
- 贪心题目循环和控制台折行
- HDOJ 1009
- 【解题报告】【USACO】酸奶工厂
- 【解题报告】【】交谊舞
- POJ 1328
- Best Cow Line
- HDU 1009 Fatmouse's Trade
- POJ2377 Bad Cowtractors
- 贪心 hdu 1003
- 最大容器
- 满足和为定值的两个数或多个数
- Codeforces Round #300
- HUD1052 __ P2 1002 __ Tian Ji -- The Horse Racing
- 2015年国家集训队测试 BZOJ3816矩阵变幻