题目 | Range Sums
AtCoder Beginner Contest 238
E - Range Sums
https://atcoder.jp/contests/abc238/tasks/abc238_e
Time Limit: 2 sec / Memory Limit: 1024 MB
Score :
Problem Statement
Takahashi has a secret integer sequence
You want to guess the contents of
- The
-th information: the value .
Is it possible to determine the sum of all elements in
Constraints
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
If it is possible to determine the sum of all elements in Yes
; otherwise, print No
.
Sample Input 1
3 3
1 2
2 3
2 2
Sample Output 1
Yes
From the first and second information, we can find the value
Sample Input 2
4 3
1 3
1 2
2 3
Sample Output 2
No
We can determine the sum of the first
Sample Input 3
4 4
1 1
2 2
3 3
1 4
Sample Output 3
Yes
The fourth information directly gives us the sum of all elements.
我的笔记
如果能想到并查集这题非常的简单。
首先有
如下图,表示的就是 1 6;2 4;2 6;5 8 这四个联通,最后 0 和 8 联通,即可以求出和。
求联通,很简单想到用并查集,因此初始化一个大小为
另外,这题必须要用路径优化,否则会有两个测试点 TLE,按秩合并倒不重要,实测按秩合并效率反而略低。
源码
#include <bits/stdc++.h>
#define MAXN 200010
using namespace std;
int fa[MAXN];
inline void init(int n)
{
for (int i = 0; i < n; i++)
fa[i] = i;
}
int find(int x)
{
return x == fa[x] ? x : (fa[x] = find(fa[x]));
}
inline void merge(int i, int j)
{
fa[find(i)] = find(j);
}
int main(void)
{
ios::sync_with_stdio(false);
int N, Q;
cin >> N >> Q;
init(N + 1);
while (Q--)
{
int l, r;
cin >> l >> r;
merge(l - 1, r);
}
if (find(0) == find(N))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi