当前位置: 移动技术网 > IT编程>开发语言>C/C++ > cf1136D. Nastya Is Buying Lunch(贪心)

cf1136D. Nastya Is Buying Lunch(贪心)

2019年03月18日  | 移动技术网IT编程  | 我要评论

题意

题目链接

给出一个排列,以及\(m\)个形如\((x, y)\)的限制,表示若\(x\)\(y\)之前则可以交换\(x, y\)

\(n\)位置上的数最多能前进几步

\(n \leqslant 3* 10^5, m \leqslant 5 * 10^5\)

sol

每次遇到这种动来动去的题基本都做不出来qwq

我最开始想到的是图论模型,然后发现不管怎么建都有反例。结果标算是个神仙贪心?。。

考虑这样一种贪心:从前往后处理每一个数,记一个\(num\)数组表示该位置的数最多能往后移动几次,每次把当前数的限制条件加到\(num\)里。如果当前的\(num\)大于等于和开始时最后一个数的距离,那么\(ans++\)。(好像看代码会更明白一些)

#include<bits/stdc++.h> 
#define pair pair<int, int>
#define mp(x, y) make_pair(x, y)
#define fi first
#define se second
//#define int long long 
#define ll long long 
#define ull unsigned long long 
#define fin(x) {freopen(#x".in","r",stdin);}
#define fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int maxn = 1e6 + 10, mod = 1e9 + 7, inf = 1e9 + 10;
const double eps = 1e-9;
template <typename a, typename b> inline bool chmin(a &a, b b){if(a > b) {a = b; return 1;} return 0;}
template <typename a, typename b> inline bool chmax(a &a, b b){if(a < b) {a = b; return 1;} return 0;}
template <typename a, typename b> inline ll add(a x, b y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename a, typename b> inline void add2(a &x, b y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename a, typename b> inline ll mul(a x, b y) {return 1ll * x * y % mod;}
template <typename a, typename b> inline void mul2(a &x, b y) {x = (1ll * x * y % mod + mod) % mod;}
template <typename a> inline void debug(a a){cout << a << '\n';}
template <typename a> inline ll sqr(a x){return 1ll * x * x;}
template <typename a, typename b> inline ll fp(a a, b p, int md = mod) {int b = 1;while(p) {if(p & 1) b = mul(b, a);a = mul(a, a); p >>= 1;}return b;}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int n, m, p[maxn], num[maxn];
vector<int> v[maxn];
signed main() {
    n = read(); m = read();
    for(int i = 1; i <= n; i++) p[i] = read();
    for(int i = 1; i <= m; i++) {
        int x = read(), y = read();
        v[y].push_back(x);
    }
    for(auto &x : v[p[n]]) num[x]++;
    int ans = 0;
    for(int i = n - 1; i >= 1; i--) {
        if(num[p[i]] >= n - ans - i) ans++;
        else for(auto &x : v[p[i]]) num[x]++;
    }
    cout << ans;
    return 0;
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网