建立一个数组high,若一对关系指明Ai与Bi可以互相看见(Ai < Bi),则把数组high中下标为Ai + 1到Bi - 1的数都减去1,意为Ai到Bi之间的牛的身高至少比它们少1。
再加一个辅助数组sup可以将时间复杂度由O(NM)降到O(N + M)。
代码实现如下:
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (register int i = a; i <= b; i++) const int maxn = 1e4 + 5; int n, p, h, r; int sup[maxn], high[maxn]; bool vis[maxn][maxn]; int read() { int x = 0, flag = 0; char ch = ‘ ‘; while (ch != ‘-‘ && (ch < ‘0‘ || ch > ‘9‘)) ch = getchar(); if (ch == ‘-‘) { flag = 1; ch = getchar(); } while (ch >= ‘0‘ && ch <= ‘9‘) { x = (x << 1) + (x << 3) + ch - ‘0‘; ch = getchar(); } return flag ? -x : x; } void write(int x) { if (x < 0) { putchar(‘-‘); x = -x; } if (x > 9) write(x / 10); putchar(x % 10 + ‘0‘); } int main() { n = read(), p = read(), h = read(), r = read(); rep(i, 1, r) { int u, v; u = read(), v = read(); if (u > v) swap(u, v); if (vis[u][v]) continue; sup[u + 1]--; sup[v]++; vis[u][v] = 1; } rep (i, 1, n) { high[i] = high[i - 1] + sup[i]; write(h + high[i]); printf("\n"); } return 0; }
值得注意的是,本题关系对是有可能重复给出的,因此我用了bool数组vis来判断,然而这是一个二维数组,很有可能爆空间,此题只是勉强卡过,更好的做法是使用map。
代码实现如下:
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (register int i = a; i <= b; i++) const int maxn = 1e4 + 5; int n, p, h, m; int sup[maxn], high[maxn]; map<pair<int, int>, bool> existed; int read() { int x = 0, flag = 0; char ch = ‘ ‘; while (ch != ‘-‘ && (ch < ‘0‘ || ch > ‘9‘)) ch = getchar(); if (ch == ‘-‘) { flag = 1; ch = getchar(); } while (ch >= ‘0‘ && ch <= ‘9‘) { x = (x << 1) + (x << 3) + ch - ‘0‘; ch = getchar(); } return flag ? -x : x; } void write(int x) { if (x < 0) { putchar(‘-‘); x = -x; } if (x > 9) write(x / 10); putchar(x % 10 + ‘0‘); } int main() { n = read(), p = read(), h = read(), m = read(); rep(i, 1, m) { int u, v; u = read(), v = read(); if (u > v) swap(u, v); if (existed[make_pair(u, v)]) continue; sup[u + 1]--; sup[v]++; existed[make_pair(u, v)] = 1; } rep (i, 1, n) { high[i] = high[i - 1] + sup[i]; write(h + high[i]); printf("\n"); } return 0; }
原文地址:https://www.cnblogs.com/Kirisame-Marisa/p/10803325.html
时间: 2024-11-05 20:43:15