2018杭电多校暑假 Distinct Values hdoj 6301

针对DistinctValues算法问题,采用更新左端点的方式简化了复杂的条件判断,并通过集合维护不重复的元素,确保找到字典序最小的数组。该方法提高了算法效率,避免了超时风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Distinct Values

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3336    Accepted Submission(s): 523

 

Problem Description

Chiaki has an array of n positive integers. You are told some facts about the array: for every two elements ai and aj in the subarray al..r (l≤i<j≤r), ai≠ajholds.
Chiaki would like to find a lexicographically minimal array which meets the facts.

 

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:The first line contains two integers n and m (1≤n,m≤105) -- the length of the array and the number of facts. Each of the next m lines contains two integers li and ri (1≤li≤ri≤n).
It is guaranteed that neither the sum of all n nor the sum of all m exceeds 106.

Output

For each test case, output n integers denoting the lexicographically minimal array. Integers should be separated by a single space, and no extra spaces are allowed at the end of lines.

 

Sample Input

3 2 1 1 2 4 2 1 2 3 4 5 2 1 3 2 4

 

Sample Output

1 2 1 2 1 2 1 2 3 1 1

 

题解:一开始手动操作缝缝补补,各种情况判断来判断去非常麻烦,加了set之后还有超时的风险,换种思路发现其实也是比较简单的,把每个位置的左端点都写出来,表示这个点到左端点的值都不能重复,当左端点更新之后,再把前面的去区间里的值加回set里,定一个下标逐步遍历即可

 code:

#include<bits/stdc++.h>
using namespace std;
const double PI=acos(-1.0);
typedef long long ll;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define clr(x) memset(x,0,sizeof(x))
int ans[100005];
int pre[100005];
int main(){
	//本地测试
	#ifdef ONLINE_JUDGE
	#else
    freopen("C://Users//yan//Desktop//in.txt","r",stdin);
	#endif
	ios::sync_with_stdio(false);//取消同步
	std::cin.tie(0);//解除cin与cout的绑定,进一步加快执行效率。
	int t;
	cin>>t;
	while(t--){
		int n,m;
		clr(ans);
		cin>>n>>m;
		rep(i,1,n+1) pre[i]=i;//初始化左边的端点 
		rep(i,0,m){
			int l,r;
			cin>>l>>r;
			pre[r]=min(pre[r],l); 
		}
		per(i,1,n){
			pre[i]=min(pre[i],pre[i+1]);//倒着更新左边的端点 
		}
		set<int> v;
		v.clear();
		int pos=1;//下标 
		rep(i,1,n){
			v.insert(i);//初始化set里面的数字 
		}
		rep(i,1,n+1){
			while(pos<pre[i]){//pos小于左边的区间说明前面的数字要加回set里 
				v.insert(ans[pos]);
				pos++;
			}
			ans[i]=*v.begin();//等于set里最小的 
			v.erase(ans[i]);//擦去这个数 
		}
		rep(i,1,n+1){
			cout<<ans[i];
			if(i!=n){
				cout<<" ";
			} 
		}
		cout<<endl;
	} 
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值