兔子跳坑法

兔子跳坑:即用並查集維護線段上某點每次能到的的最後一個點

【題目一】

Description
一隻有追求的兔紙,不應該終日遊戲。於是它參加了一個名爲蘿蔔大戰的遊戲,啊不,比賽。

比賽開始時,場地上有NN個蘿蔔,第ii個蘿蔔具有美味度DiDi。更加詭異的是,第ii個蘿蔔會在第TiTi秒末消失。

雖然兔紙每秒至多吃掉11個蘿蔔,但是它仍然急切地想要知道,它能吃掉蘿蔔美味度之和的最大值是多少。

Input Specification
第 11 行, 11 個整數 NN。

第 22 行到第 N+1N+1 行, 22 個整數Di,TiDi,Ti。

Output Specification
第 11 行, 11 個整數, 表示美味度之和的最大值。

Input and Output Sample
[input #1]
2
1 2
2 1

[output #1]
3

[input #2]
3
1 2
2 2
3 1

[output #2]
5
Extra Input Sample

Extra Output Sample

Data Restriction
對於 10% 的數據,1≤N≤51≤N≤5
對於 30% 的數據, 1≤N≤1,000 1≤Di,Ti≤1,0001≤N≤1,000 1≤Di,Ti≤1,000。
對於 60% 的數據, 1≤N≤100,000 1≤Di,Ti≤100,0001≤N≤100,000 1≤Di,Ti≤100,000。
對於 80% 的數據, 1≤N≤100,000 1≤Di,Ti≤1,000,000,0001≤N≤100,000 1≤Di,Ti≤1,000,000,000。
對於 100% 的數據, 1≤N≤1,000,000 1≤Di,Ti≤1,000,000,0001≤N≤1,000,000 1≤Di,Ti≤1,000,000,000。
時間限制: 11 秒


【題目二】

Description
某校大門外長度爲 LL 的馬路上有一排樹, 每兩棵相鄰的樹之間的間隔都是 11 米。我們可以把馬路看成一個數軸, 馬路的一端在數軸 11 的位置, 另一端在 LL 的位置; 數軸上的每個整數點, 即 1,2,...,L1,2,...,L 的位置, 都種有一棵樹。

由於馬路上N個區域 [L1,R1],[L2,R2],...,[LN,RN][L1,R1],[L2,R2],...,[LN,RN] 要用來建地鐵, 區域之間可能有重合的部分。現在要把這些區域中的樹(包括區域端點處的兩棵樹)移走。

你的任務是計算每次移走這些樹後, 馬路上還有多少棵樹。

Input Specification
第 11 行, 22 個整數 NN 和 LL。

第 22 行到第 N+1N+1 行, 22 個整數 LiLi 和 RiRi。

Output Specification
第 11 行到第 NN 行, 11 個整數, 表示移走之後樹的數量。

Input and Output Sample
[input]
2 4
2 3
3 4

[output]
2
1
Restriction
對於50%的數據, N,Li,Ri≤1,000N,Li,Ri≤1,000。
對於100%的數據, N,L,Li,Ri≤100,000N,L,Li,Ri≤100,000。


【代碼1】

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#define ll long long
#define maxn 1000006
using namespace std;
struct data{
    int t;ll d;
    bool operator <(const data&b)const{
		return (d>b.d);
	}
}e[maxn];
int n,cnt=0,fa[maxn];
ll ans=0;
int get(){
    char c;while(!isdigit(c=getchar()));
    int v=c-48;while(isdigit(c=getchar()))v=v*10+c-48;
    return v;
}
int getfa(int x){
    if(fa[x]==x)return fa[x];
    else return fa[x]=getfa(fa[x]);
}
void init(){
    n=get();ll x;int y;int mx=0;
    for(int i=1;i<=n;++i){
	    x=get();y=get();
	    if(y>n)ans+=x;
	    else{
		    e[++cnt].d=x;
		    e[cnt].t=y;
		    mx=max(mx,y);
		}
	}
	sort(e+1,e+1+cnt);
	for(int i=1;i<=mx;++i)fa[i]=i;
	for(int i=1;i<=cnt;++i){
	    int f=getfa(e[i].t);
	    if(f){
		    fa[f]=f-1;
		    ans+=e[i].d;
		}
	}
	printf("%lld\n",ans);
}
int main(){
    init();
    return 0;
}
【代碼2】
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#define maxn 100006
using namespace std;
int n,L,fa[maxn];
int getfa(int x){
    if(fa[x]==x)return fa[x];
    else return (fa[x]=getfa(fa[x]));
}
int main(){
    scanf("%d%d",&n,&L);
    int ans=L;int l,r;
    for(int i=1;i<=L;++i)fa[i]=i;
    for(int i=1;i<=n;++i){
	    scanf("%d%d",&l,&r);
	    int f=getfa(r);
	    while(l<=f){
		    fa[f]=f-1;
		    --ans;
		    f=getfa(f);
		}
		printf("%d\n",ans);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章