D. Constructing the Array(结构体排序与dfs)

  • 题面

  • 题意:给你一个长度为 n \small n 0 \small 0 数组,然后操作 n \small n 次,每第 i \small i ( \small ( 1 i n \small1\leq i \leq n ) \small ) 次使得最长连续 0 \small 0 的区间 ( \small ( l   ,   \small l~,~ r \small r ) \small ) a n s [ m i d ] = i \small ans[mid]= i

  • 解决思路:可以考虑用结构体将每次操作的左端点、右端点、区间长度保存下来 ( \small ( 此过程不难想到可以用 d f s \small dfs 处理 ) \small ) ,再进行结构体排序,按长度降序,左端点升序排序,遍历每个操作 i \small i ,执行 a n s [ m i d ] = i \small ans[mid] = i 即可。

  • AC代码

//优化
#pragma GCC optimize(2)
//C
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
//C++
#include<unordered_map>
#include<algorithm>
#include<iostream>
#include<istream>
#include<iomanip>
#include<climits>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
//宏定义
#define N 110
#define DoIdo main
//#define scanf scanf_s
#define it set<ll>::iterator
//定义+命名空间
typedef long long ll;
typedef unsigned long long ull;
const ll mod = 1e9 + 7;
const ll INF = 1e18;
const int maxn = 2e5 + 10;
using namespace std;
//全局变量
struct node {
	int l, r;
	int val;
}q[maxn];
int cnt;
int ans[maxn];
//函数区
ll max(ll a, ll b) { return a > b ? a : b; }
ll min(ll a, ll b) { return a < b ? a : b; }
void dfs(int l, int r) {
	if (l > r) return;
	q[++cnt].l = l;
	q[cnt].r = r;
	q[cnt].val = (r - l + 1);
	int mid = l + r >> 1;
	dfs(l, mid - 1);
	dfs(mid + 1, r);
}
bool cmp(node a, node b) {
	if (a.val == b.val) return a.l < b.l;
	return a.val > b.val;
}
//主函数
int DoIdo() {
 
	ios::sync_with_stdio(false);
	cin.tie(NULL), cout.tie(NULL);
 
	int T;
	cin >> T;
 
	while (T--) {
		cnt = 0;
		int n;
		cin >> n;
 
		dfs(1, n);
 
		sort(q + 1, q + cnt + 1, cmp);
 
		for (int i = 1; i <= n; i++) {
			int mid = (q[i].l + q[i].r) / 2;
			ans[mid] = i;
		}
 
		for (int i = 1; i <= n; i++) cout << ans[i] << " ";
		cout << endl;
	}
	return 0;
}
//分割线---------------------------------QWQ
/*
 
 
 
*/

猜你喜欢

转载自blog.csdn.net/qq_45739057/article/details/106209807