码迷,mamicode.com
首页 > 其他好文 > 详细

OpenJudge POJ C19C 贪心

时间:2019-07-08 23:48:53      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:style   type   移动   const   ret   color   i++   lse   return   

https://cn.vjudge.net/contest/309482#problem/C

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 400005;
int a[MAXN][2];
int ans;
int main() {
        int T;
        scanf("%d", &T);
        while (T--) {
                int n;
                scanf("%d", &n);
                for (int i = 0; i < n; i++) {
                        a[i][0] = a[i][1] = 0;
                }
                long long ans = 0;
                for (int i = 0, x, y; i < 2 * n; i++) {
                        scanf("%d %d", &x, &y);
                        x--;
                        if (y >= 2) { //Y>2的全部移动到2
                                ans += y - 2;
                                y = 1;
                        } else {  //Y<1的全部移动到1
                                ans += 1 - y;
                                y = 0;
                        }
                        if (x < 0) { //X<1的全部移动到1
                                ans -= x;
                                x = 0;
                        }
                        if (x >= n) { //X>N的全部移动到N
                                ans += x - (n - 1);
                                x = n - 1;
                        }
                        a[x][y]++;
                }
                //cout<<" : "<<ans<<endl;
                for (int i = 0; i < n; i++) {
                        //每个位置固定留一个
                        a[i][0]--;
                        a[i][1]--;
                        if (1LL * a[i][0]*a[i][1] < 0) { //如果出现上下一个多的一个少的
                                int t = min(abs(a[i][0]), abs(a[i][1]));
                                if (a[i][0] > 0) {
                                        a[i][0] -= t;
                                        a[i][1] += t;
                                } else {
                                        a[i][1] -= t;
                                        a[i][0] += t;
                                }
                                ans += t;
                        }
                        //有多的就从左边移动到右边且如果缺的话也将缺的值传递给右边
                        ans += abs(a[i][0]);
                        a[i + 1][0] += a[i][0];
                        ans += abs(a[i][1]);
                        a[i + 1][1] += a[i][1];
                }
                cout << ans << endl;
        }
        return 0;
}

 

OpenJudge POJ C19C 贪心

标签:style   type   移动   const   ret   color   i++   lse   return   

原文地址:https://www.cnblogs.com/Aragaki/p/11154550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!