LOJ516 DP一般看规律(然额并不是DP的呢~气不气)

冒险寮

【题目描述】

给定一个长度为 n 的序列 a,一共有 m 个操作。

每次操作的内容为:给定 x,y,序列中所有 x 会变成 y。

同时我们有一份代码:

int ans = 2147483647;
for (int i = 1; i <= n; i++) {
    for (int j = i + 1; j <= n; j++) {
        if (a[i] == a[j])
            ans = std::min(ans, j - i);
    }
}
std::cout << ans << std::endl;

请在每次修改后输出代码运行的结果。

【输入格式】

第一行两个数,表示 n,m。

第二行 n 个数,表示 a1,a2,⋯ ,an。

然后 m 行每行两个数 x 和 y,表示序列中所有 x 会变成 y。

【输出格式】

对于每次修改,输出答案。

【样例输入】

5 10

2 7 6 3 8 

6 1

7 1

1 3

5 6

1 7

9 5

1 10

7 6

7 5

3 9

【样例输出】

2147483647

1

1

1

1

1

1

1

1

1

【备注】

1≤n,m≤100000

每个出现的数字绝对值在 int 范围内。

【题目分析】

不是DP,不是DP,不是DP。。。。。

首先对于序列上一点,它对答案的贡献只有与它的前驱和后驱(以为用平衡树维护的我看了看4级就放心了)。方法比较简单,代码也很好写,emmm,STL大法好。(暴力合并两个set就行了)

【代码~】

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e5+10;

int n,m,ans=2147483647;
map<int,set<int> > a;

void update(int x,int y)
{
	set<int>::iterator it=a[x].lower_bound(y);
	if(it!=a[x].end())
	  ans=min(ans,*it-y);
	if(it!=a[x].begin())
	  ans=min(ans,y-*--it);
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;++i)
	{
		int x;
		scanf("%d",&x);
		update(x,i);
		a[x].insert(i);
	}
	while(m--)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		if(x^y)
		{
			if(a[x].size()>a[y].size())
			  swap(a[x],a[y]);
			for(set<int>::iterator it=a[x].begin();it!=a[x].end();it++)
			{
				update(y,*it);
				a[y].insert(*it);
			}
			a[x].clear();
		}
		printf("%d\n",ans);
	}
	return 0;
}

 

posted @ 2018-10-15 21:00  Ishtar~  阅读(136)  评论(0)    收藏  举报