题意:已知有n个人,从第一个人开始每个人被安排在第ai个空座上,有m组询问,问某人所坐的位置。
分析:
1、用树状数组维护空座的个数,方法:
将所有的空座初始化为1,sum(x)则表示从座位1到座位x空座的个数。
2、对于每个人,根据sum(mid),二分找使sum(mid)大于等于a[i]的最小的mid,即第ai个空座的位置,并将该位置加上-1,则该位置的值变为0,从而不参与空座数的统计。
3、vis[q]即为标号为q的人所坐的位置。
#include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define lowbit(x) (x & (-x)) const double eps = 1e-8; inline int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a > b ? 1 : -1; } typedef long long LL; typedef unsigned long long ULL; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const LL LL_INF = 0x3f3f3f3f3f3f3f3f; const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const int MAXN = 50000 + 10; const int MAXT = 10000 + 10; using namespace std; int vis[MAXN]; int a[MAXN]; int z[MAXN]; int n; int sum(int x){ int ans = 0; for(int i = x; i >= 1; i -= lowbit(i)){ ans += z[i]; } return ans; } void add(int x, int value){ for(int i = x; i <= n; i += lowbit(i)){ z[i] += value; } } int solve(int x){ int l = 1, r = n; while(l < r){ int mid = l + (r - l) / 2; if(sum(mid) >= x) r = mid; else l = mid + 1; } return r; } int main(){ while(scanf("%d", &n) == 1){ memset(vis, 0, sizeof vis); for(int i = 1; i <= n; ++i){ scanf("%d", &a[i]); add(i, 1); } for(int i = 1; i <= n; ++i){ vis[i] = solve(a[i]); add(vis[i], -1); } int m; scanf("%d", &m); bool flag = true; while(m--){ int q; scanf("%d", &q); if(flag) flag = false; else printf(" "); printf("%d", vis[q]); } printf("\n"); } return 0; }
时间: 2024-10-14 07:04:51