A 黑白边
有n个点,m条边,每条边都分为黑边和白边,现在要选一些边,使得所有点都可以相互连通,要求用白边的条数最少。
看到所有的点都相互连通,就可以想到生成树,所以把所有的白边和黑边分类,先用黑色的边构造生成树,再用白色的,这样就可以使所用的白色的边最少。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <deque>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
#define lowbit(a) (a & (-a))
#define ll long long
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
const int minn = 1e3 + 10;
const double PI = acos(-1.0);
#define mod 10000
#define eps 1e-10
/*------------------------------------------------------*/
struct edge
{
int u, v, w;
} a[maxn];
int f[maxn];
int n, m;
bool cmp(edge x, edge y)
{
return x.w < y.w;
}
int Find(int x)
{
if (x == f[x])
return x;
return f[x] = Find(f[x]);
}
void join(int x, int y)
{
int fx = Find(x);
int fy = Find(y);
if (fx != fy)
f[fx] = fy;
}
void init()
{
for (int i = 0; i <= n; i++)
f[i] = i;
}
int kruskal()
{
int sum = 0, ans = 0;
for (int i = 1; i <= m; i++)
{
int fu = Find(a[i].u);
int fv = Find(a[i].v);
if (fu != fv)
{
sum++;
join(a[i].u, a[i].v);
if (a[i].w == 1)
ans++;
}
if (sum == n - 1)
break;
}
if (sum == n - 1) return ans;
return -1;
}
int main()
{
scanf("%d %d",&n,&m);
init();
for (int i = 1; i <= m; i++)
scanf("%d %d %d", &a[i].u, &a[i].v, &a[i].w);
sort(a + 1, a + m + 1, cmp);
int ans=kruskal();
printf("%d\n",ans);
return 0;
}
B、最好的宝石
有n个宝石,第i个宝石的价值为w[i],然后有m个操作:
第一种是Change x y 把第x个宝石的价值改成 y ;
第二种是 Ask l r 询问区间[l,r]内宝石的最大价值,和最大价值的宝石有多少个。
线段树维护区间最大值,特殊的是这题还需要输出这段区间内最大值的个数,其实就是在pushup的时候判断一下,取左右两个子节点的最大值,然后让其父节点的值更新为这个最大值,并且把个数更新一下就可以了。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <deque>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
#define lowbit(a) (a & (-a))
#define ll long long
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
const int minn = 1e3 + 10;
const double PI = acos(-1.0);
#define mod 10000
#define eps 1e-10
/*------------------------------------------------------*/
struct node
{
int l, r, w, sum;
} Tree[maxn << 2];
int a[maxn << 2];
int n, m, maxw, maxsum;
string s;
void pushup(int rt)
{
Tree[rt].w = max(Tree[rt << 1].w, Tree[rt << 1 | 1].w);
Tree[rt].sum = 0;
if (Tree[rt].w == Tree[rt << 1].w)
Tree[rt].sum += Tree[rt << 1].sum;
if (Tree[rt].w == Tree[rt << 1 | 1].w)
Tree[rt].sum += Tree[rt << 1 | 1].sum;
}
void build(int rt, int l, int r)
{
Tree[rt] = {l, r, a[l], 1};
if (l == r)
return;
else
{
int mid