跳到正文

个人记录

最近做题的小技巧总结

LJY_ljy约 87 分钟
原文
文章信息与版本

文章信息

发布
2022年7月21日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 87 分钟

版本

  1. v1当前

1.CF1542B Plus and Multiply

1.在带余除法时一定要考虑到除数大于余数(同快速幂中 % 1)

2.在带余除法时一定要注意余数为1可能会导致死循环!

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

inline long long read() {
    register long long x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

long long x, n, a, b;

int main() {
    long long t = read();
    while (t--) {
        n = read(); a = read(); b = read();
        if (a == 1) {
            if (n % b == 1 || b == 1) printf("Yes\n");
            else printf("No\n");
        } else {
            long long t = 1;
            bool flag = false;
            while (t <= n / a) {
                if ((n - t) % b == 0) {
                    flag = true;
                    break;
                }
                t *= a;
            }
            if ((n - t) % b == 0) flag = true;
            if (flag) printf("Yes\n");
            else printf("No\n");
        }
    }
    return 0;
}

2.UVA548 树 Tree

stringstream的一些小用法:

1.stringstream适合输入没有字符串个数,长度的无限输入(例如UVA548)

2.头文件:

C++
#include <sstream>

定义一个stringstream:

C++
stringstream ss(str); // ss是stringstream类型的一个变量名,str是字符串的变量名
C++
while (ss >> G[++cnt][eid]);//不断地输入一个整数数组
C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <sstream>
#define MAXN 10010
#define INF 1000000000
using namespace std;

struct node {
    int w, leaf;
} dp[MAXN];
string str;
int n, eid, G[MAXN][2], cnt, Root;
int child[MAXN][2];

inline int dfs(int L1, int R1, int L2, int R2) {
    if (L1 > R1) return -1;
    int root = G[R2][1], index = -1;
    for (int i = L1; i <= R1; i++) {
        if (G[i][0] == root) {
            index = i;
            break;
        }
    }
    if (index == -1) return -1;
    child[G[index][0]][0] = dfs(L1, index - 1, L2, L2 + index - 1 - L1);
    child[G[index][0]][1] = dfs(index + 1, R1, R2 - 1 - R1 + (index + 1), R2 - 1);
    cnt = 0;
    return G[index][0];
}

inline void dfs2(int u) {
    if (child[u][0] == -1 && child[u][1] == -1) {
        dp[u].w = u;
        dp[u].leaf = u;
        return;
    }
    int minn = INF;
    if (child[u][0] != -1) {
        dfs2(child[u][0]);
        if (dp[child[u][0]].w + u < dp[u].w) {
            dp[u].w = dp[child[u][0]].w + u;
            dp[u].leaf = dp[child[u][0]].leaf;
        } else if (dp[child[u][0]].w + u == dp[u].w && dp[child[u][0]].leaf < dp[u].leaf) {
            dp[u].leaf = dp[child[u][0]].leaf;
        }
    }
    if (child[u][1] != -1) {
        dfs2(child[u][1]);
        if (dp[child[u][1]].w + u < dp[u].w) {
            dp[u].w = dp[child[u][1]].w + u;
            dp[u].leaf = dp[child[u][1]].leaf;
        } else if (dp[child[u][1]].w + u == dp[u].w && dp[child[u][1]].leaf < dp[u].leaf) {
            dp[u].leaf = dp[child[u][1]].leaf;
        }
    }
}

inline void Calc() {
    memset(child, -1, sizeof(child));
    for (int i = 0; i <= n; i++) {
        dp[G[i][0]].w = INF;
        dp[G[i][0]].leaf = INF;
    }
    dfs(1, n, 1, n);
    Root = G[n][1];
    dfs2(Root);
    printf("%d\n", dp[Root].leaf);
}

int main() {
    while (getline(cin, str)) {
        stringstream ss(str);
        while (ss >> G[++cnt][eid]);
        if (!eid) {
            n = cnt - 1;
            cnt = 0;
        }
        if (eid) {
            Calc();
        }
        eid ^= 1;
    }
    return 0;
}

3.UVA10817 校长的烦恼 Headmaster’s Headache

记忆化搜索,是dp的另一种形式

在记忆化搜索中不需要dfs传递极值,而是要用ans数组储存,相当于剪枝,降低代码的时间复杂度

一定要记得引用,剪枝,访问过就不用遍历第二次。

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <sstream>
#define INF 1000000000
using namespace std;

int S, M, N;
int teach[130], cost[130];
int ans[130][260][260], minn;
string str;

///记忆化搜索,是dp的另一种形式
///在记忆化搜索中不需要dfs传递极值,而是要用ans数组储存,相当于剪枝,降低代码的时间复杂度
inline int dp(int n, int S0, int S1, int S2) {
    if (n == M + N + 1) {
        if (S2 == (1 << S) - 1) return 0; ///注意dfs顺序,第一个返回的是叶子结点,所以要返回0
        else return INF;
    }
    int &cnt = ans[n][S1][S2]; ///一定要记得引用
    if (cnt >= 0) return cnt; ///剪枝,访问过就不用遍历第二次
    cnt = INF;
    if (n >= M + 1) cnt = min(cnt, dp(n + 1, S0, S1, S2));
    int S = (S0 & teach[n]), S3 = (S1 & teach[n]);
    S0 ^= teach[n];
    S1 ^= teach[n];
    S1 |= S;
    S2 |= S3;
    cnt = min(cnt, dp(n + 1, S0, S1, S2) + cost[n]);
    return cnt; ///记得dfs是int类型,且要返回
}

int main() {
    while (true) {
        minn = INF;
        memset(teach, 0, sizeof(teach));
        memset(ans, -1, sizeof(ans));
        memset(cost, 0, sizeof(cost));
        getline(cin, str);
        stringstream ss(str);
        ss >> S >> M >> N;
        if (S == 0) break;
        for (int i = 1; i <= M + N; i++) {
            getline(cin, str);
            stringstream ss(str);
            ss >> cost[i];
            int x;
            while (ss >> x) teach[i] |= (1 << (x - 1));
        }
        printf("%d\n", dp(1, (1 << S) - 1, 0, 0));
    }
    return 0;
}

同UVA1099,看到n在10~15之间浮动时,可以试试状压dp。

4.UVA1099 Sharing Chocolate

位运算的一些小技巧:

1.Cs(s0) = s ^ s0 而不是 s - s0; S代表的是一个集合,所以要用差集(^)

2.枚举S集合的所有子集的小技巧:

C++
for (int S0 = (S - 1) & S; S0; S0 = (S0 - 1) & S)

证明如下: 设S = 1100110,那么我们可以从S的最大非空真子集开始枚举,就是要找到1100100 <==>将S最后一个1去掉,初赛曾经考过。因为S - 1就会将S的最后一个1变成0并且将原先最后一个1后面的0变成1,&一下就可以了

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 110
#define MAXS 32800
using namespace std;

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

int n, x, y, a[MAXN], Sum[MAXS], eid;
bool dp[MAXN][MAXS];
bool visited[MAXN][MAXS], flag;

inline int only_one(int S) {
	int cnt = 0;
	while (S) {
		S = (S - 1) & S;
		cnt++;
	}
	return cnt;
} 

inline bool dfs(int x, int S) {
    if (visited[x][S]) return dp[x][S];
	visited[x][S] = true;
	if (Sum[S] % x != 0) return dp[x][S] = false; ///临界,S只有一块巧克力组成 
	if (only_one(S) == 1) return dp[x][S] = true;
    int y = Sum[S] / x;
    for (int S0 = (S - 1) & S; S0; S0 = (S0 - 1) & S) { ///① 
       	int x1 = Sum[S0] / y, x2 = Sum[S ^ S0] / y; ///将x * y的大巧克力拆分成x1 * y + x2 * y的两块巧克力 
    	int y1 = Sum[S0] / x, y2 = Sum[S ^ S0] / x;
    	if ((Sum[S0] % y == 0) && dfs(min(x1, y), S0) && dfs(min(x2, y), S ^ S0)) return dp[x][S] = true;
    	///注意:Cs(s0) = s ^ s0 而不是 s - s0; S代表的是一个集合,所以要用差集(^) 
    	if ((Sum[S0] % x == 0) && dfs(min(x, y1), S0) && dfs(min(x, y2), S ^ S0)) return dp[x][S] = true;
    	///因为一块大巧克力只能拆分成两块同长/同宽的巧克力,所以可以这么转移
		///拆分巧克力比拼凑巧克力好转移,因为拼凑巧克力可能拼凑不出来一个矩形 
	}
	return dp[x][S] = false;
}

/*
①是一种枚举二进制数代表的集合的所有子集的二进制方法,证明如下:
设S = 1100110,那么我们可以从S的最大非空真子集开始枚举,就是要找到1100100
<==>将S最后一个1去掉,初赛曾经考过。因为S - 1就会将S的最后一个1变成0并且将原先最后一个1后面的0变成1,&一下就可以了 
*/

int main() {
    while (scanf("%d", &n) == 1 && n != 0) {
    	eid++;
        flag = true;
        memset(Sum, 0, sizeof(Sum));
        memset(visited, false, sizeof(visited));
        memset(dp, false, sizeof(dp));
        x = read(); y = read();
        for (int i = 1; i <= n; i++) a[i] = read();
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < (1 << (i - 1)); j++) {
                Sum[j | (1 << (i - 1))] = Sum[j] + a[i];
            }
        }
        if (Sum[(1 << n) - 1] != x * y) flag = false;
        if (dfs(min(x, y), (1 << n) - 1) && flag)  printf("Case %d: Yes\n", eid);
        else printf("Case %d: No\n", eid);
    }
    return 0;
}

5.UVA11020 Efficient Solutions

set中迭代器的使用:

C++
it->c //指向元素
C++
multiset<node>::iterator it; //定义一个可重集set
C++
it = S.lower_bound(groom);///lower_bound()是指找到从begin()到end()第一个大于等于val的地址
C++
it = S.upper_bound(groom);///upper_bound是指找到从begin()到end()第一个大于val的地址
C++
S.erase(it++); ///it先加,再运行it原来的地址
C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
using namespace std;

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

struct node {
    int l, c;
    bool operator < (const node &a) const {
        if (l != a.l) return l < a.l;
        return c < a.c;
    }
};

int N, n;
multiset<node> S;
multiset<node>::iterator it;

int main() {
    N = read();
    for (int u = 1; u <= N; u++) {
        S.clear();
        printf("Case #%d:\n", u);
        n = read();
        for (int i = 1; i <= n; i++) {
            node groom;
            groom.l = read(); groom.c = read();
            it = S.lower_bound(groom);///lower_bound()是指找到从begin()到end()第一个大于等于val的地址
            if (it == S.begin() || (--it)->c > groom.c) {
                S.insert(groom);
                it = S.upper_bound(groom);///upper_bound是指找到从begin()到end()第一个大于val的地址
                while (it != S.end() && it->c >= groom.c) {
                    S.erase(it++); ///it先加,再运行it原来的地址
                }
            }
            printf("%d\n", S.size());
        }
        if (u != N)
            printf("\n");
    }
    return 0;
}

6.CF479E Riding in a Lift

1.C++中取余函数的一些用法:

1.C++ 中 % 只适用于int而不适用与long long, 所以遇到统计方案数问题时最好就用int。

2.在带余除法时一定要考虑到除数大于余数(同快速幂中 % 1)

在带余除法时一定要注意余数为1可能会导致死循环! (同CF1542B)

2.动态规划的优化新方法: 差分

一段区间要加上一个固定值,并且最后求的是1~n的和,那么就可以用差分d数组在O(1)的时间内解决朴素算法O(n)才能解决的状态转移。

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#define MAXN 5010
#define MOD 1000000007
using namespace std;

inline int read() {
	register int x = 0, f = 1;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (isdigit(ch)) {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * f;
}

int n, a, b, k, ans, d[MAXN][MAXN], dp[MAXN][MAXN];
struct node {
	int l[4], r[4];
	int eid;
} cut[MAXN];

int main() {
	n = read(); a = read(); b = read(); k = read();
	for (int i = 1; i <= n; i++) {
		int len = abs(i - b), cut1 = -1, cut2 = -1;
		int Minn = max(1, i - (len - 1));
		int Maxx = min(n, i + (len - 1));
		if (Minn <= b && b <= Maxx)
			cut1 = b;
		if (Minn <= i && i <= Maxx)
			cut2 = i;
		if (cut1 != -1 && cut2 != -1) {
			if (cut1 > cut2) swap(cut1, cut2);
			cut[i].l[1] = Minn; cut[i].r[1] = cut1 - 1;
			cut[i].l[2] = cut1 + 1; cut[i].r[2] = cut2 - 1;
			cut[i].l[3] = cut2 + 1; cut[i].r[3] = Maxx;
			cut[i].eid = 3;
		}
		if (cut1 == -1 && cut2 != -1) {
			cut[i].l[1] = Minn; cut[i].r[1] = cut2 - 1;
			cut[i].l[2] = cut2 + 1; cut[i].r[2] = Maxx;
			cut[i].eid = 2;
		}
		if (cut1 != -1 && cut2 == -1) {
			cut[i].l[1] = Minn; cut[i].r[1] = cut1 - 1;
			cut[i].l[2] = cut1 + 1; cut[i].r[2] = Maxx;
			cut[i].eid = 2;
		}
		if (cut1 == -1 && cut2 == -1) {
			cut[i].l[1] = Minn; cut[i].r[1] = Maxx;
			cut[i].eid = 1;
		}
	}
	dp[a][0] = 1;
	for (int i = 1; i <= k; i++) {
		for (int j = 1; j <= n; j++) {
			if (j != b) {
				for (int k = 1; k <= cut[j].eid; k++) {
					if (cut[j].l[k] <= cut[j].r[k]) {
						d[cut[j].l[k]][i] = (d[cut[j].l[k]][i] + dp[j][i - 1]) % MOD;
						d[cut[j].r[k] + 1][i] = (d[cut[j].r[k] + 1][i] + MOD - dp[j][i - 1]) % MOD;
					}
				}
			}
		}
		for (int j = 1; j <= n; j++)
			dp[j][i] = (dp[j - 1][i] + d[j][i]) % MOD;
	}
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		if (i != b)
			ans = (ans + dp[i][k]) % MOD;
	}
	printf("%d\n", (ans + MOD) % MOD);
	return 0;
}

7.UVA1625 颜色的长度 Color Length

1.memset的使用情况:

memset的时间复杂度是O(n * 一个小常数),其中n是数组长度。

如果在一组数据的输入中使用memset清空数组是OK的,但是在多组数据中用memset会T到飞起(例如UVA1625,CF1385D),这个时候应该会手动优化清空数组。

2.dp的一个小优化:贡献后移/贡献拆分。

在这道题中,不好处理的是一个字符最后一次出现的位置与第一次出现的位置的差值。

换种角度考虑,我们可以采用类似差分的方法,从第一次出现到最后一次出现-1的位置都加上1,用C[i][j]统计第一个字符串取了前i个,第二个字符串取了前j个字符,有多少个字符符合条件。

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#define MAXN 30
#define MAXL 5010
using namespace std;

int T, len1, len2;
string str1, str2;
int first_appear[MAXN][2], last_appear[MAXN][2];
int dp[MAXL][MAXL], c[MAXL][MAXL];

inline void init() {
	memset(first_appear, 0x7f, sizeof(first_appear));
	memset(last_appear, -1, sizeof(last_appear));
	len1 = str1.size(); 
	len2 = str2.size();
	for (int i = 1; i <= len1; i++) {
		last_appear[str1[i - 1] - 'A' + 1][0] = i;
		first_appear[str1[i - 1] - 'A' + 1][0] = min(first_appear[str1[i - 1] - 'A' + 1][0], i);
	}
	for (int i = 1; i <= len2; i++) {
		last_appear[str2[i - 1] - 'A' + 1][1] = i;
		first_appear[str2[i - 1] - 'A' + 1][1] = min(first_appear[str2[i - 1] - 'A' + 1][1], i);
	}
}

int main() {
	scanf("%d", &T);
	while (T--) {
		cin >> str1 >> str2;
		init();
		dp[0][0] = 0;
		for (int i = 0; i <= len1; i++) {
			for (int j = 0; j <= len2; j++) {
				if (i == 0 && j == 0) continue;
				dp[i][j] = 0x7f;
				if (i) {
					c[i][j] = c[i - 1][j];
					if (first_appear[str1[i - 1] - 'A' + 1][0] == i && first_appear[str1[i - 1] - 'A' + 1][1] > j) c[i][j]++;
					if (last_appear[str1[i - 1] - 'A' + 1][0] == i && last_appear[str1[i - 1] - 'A' + 1][1] <= j) c[i][j]--;
				}
				if (j) {
					c[i][j] = c[i][j - 1];
					if (first_appear[str2[j - 1] - 'A' + 1][1] == j && first_appear[str2[j - 1] - 'A' + 1][0] > i) c[i][j]++;
					if (last_appear[str2[j - 1] - 'A' + 1][1] == j && last_appear[str2[j - 1] - 'A' + 1][0] <= i) c[i][j]--;
				}
				if (i) dp[i][j] = min(dp[i][j], dp[i - 1][j] + c[i][j]);
				if (j) dp[i][j] = min(dp[i][j], dp[i][j - 1] + c[i][j]);
			}
		}
		printf("%d\n", dp[len1][len2]); 
	}
	return 0;
} 

8.CF269B Greenhouse Effect 与 CF713C Sonya and Problem Wihtout a Legend:

1.两者属于同一种类型的线性dp,其中CF269B是将一个序列变成非严格单调递增的数列,CF713C是将一个序列变成严格递增序列。

2.将一个序列转成非严格单调递增所需花费代价的最小值(见蓝书P267 - 269):

C++
F[i, j] = min(F[i - 1, k] + |A[i] - B[j]|);
///0 <= k <= j 决策集合只增不减,所以可以用一个变量存储O(1)实现转移
///F[i, j]表示完成前i个数的构造,其中B[i] = j时和的最小值,B[]是将a[]离散化后的结果

3.求将一个序列转成非严格单调递增需要更改的数目的最小值 = n - A[]的最长不下降子序列个数。

4.如果是转为严格递增呢?a[i] -= i 然后运行即可。

CF269B:

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAXN 5010
#define INF 1000000
using namespace std;

inline int read() {
	register int x = 0, f = 1;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (isdigit(ch)) {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * f;
} 

int dp[MAXN], a[MAXN], n, m;

int main() {
	n = read(); m = read();
	for (int i = 1; i <= n; i++) {
		a[i] = read();
		double t; cin >> t;
	}
	a[0] = -INF;
	for (int i = 1; i <= n; i++) {
		for (int j = 0; j < i; j++) {
			if (a[j] <= a[i])
				dp[i] = max(dp[i], dp[j] + 1);
		}
	}
	int ans = -INF;
	for (int i = 1; i <= n; i++) ans = max(ans, dp[i]);
	printf("%d\n", n - ans);
	return 0;
}

CF713C:

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#define MAXN 3010
#define INF 10000000000000
using namespace std;

inline long long read() {
    register long long x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

long long n, a[MAXN], A[MAXN], b[MAXN];
long long dp[MAXN][MAXN], ans = INF;

int main() {
    n = read();
    for (long long i = 1; i <= n; i++) {
        a[i] = read();
        a[i] -= i;
        b[i] = a[i];
    }
    sort(b + 1, b + 1 + n);
    long long m = unique(b + 1, b + 1 + n) - (b + 1);
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++)
            dp[i][j] = INF;
    }
    dp[0][0] = 0;
    for (long long i = 1; i <= n; i++) {
        long long Minn = dp[i - 1][0];
        for (long long j = 1; j <= m; j++) {
            Minn = min(Minn, dp[i - 1][j]);
            dp[i][j] = Minn + abs(a[i] - b[j]);
            if (i == n) ans = min(ans, dp[n][j]);
        }
    }
    printf("%lld\n", ans);
    return 0;
}

9.P4556 [Vani有约会]雨天的尾巴 /【模板】线段树合并

1.关于线段树中mid = (l + r) >> 1:

根据LRJ的写法,写成

C++
l + ((r - l) >> 1);

的写法更不容易溢出,但是血的教训:不要写成:

C++
l + (r - l) >> 1;

2.lca中将fa[][]数组直接在dfs中更新好像又快又准一些:

C++
inline void lca_dfs(int u, int f) {
    for (int i = 0; i < G[u].size(); i++) {
        int to = G[u][i];
        if (to == f) continue;
        d[to] = d[u] + 1;
        fa[to][0] = u;
        for (int j = 1; j <= t; j++)
            fa[to][j] = fa[fa[to][j - 1]][j - 1];
        lca_dfs(to, u);
    }
}

3.新芝士:线段树合并:

(为了节省线段树开辟出来的空间)

C++
///线段树动态开点部分

inline void maintain(int p) {
    tr[p].maxx = max(tr[tr[p].lc].maxx, tr[tr[p].rc].maxx);
    if (tr[tr[p].lc].maxx > tr[tr[p].rc].maxx)
        tr[p].dat = tr[tr[p].lc].dat;
    else if (tr[tr[p].rc].maxx > tr[tr[p].lc].maxx)
        tr[p].dat = tr[tr[p].rc].dat;
    else
        tr[p].dat = min(tr[tr[p].lc].dat, tr[tr[p].rc].dat);
}


inline void Insert(int p, int l, int r, int val, int add) {
    if (l == r) {
        tr[p].maxx += add;
        tr[p].dat = tr[p].maxx ? l : 0;
        return;
    }
    int mid = l + ((r - l) >> 1);
    if (val <= mid) {
        if (!tr[p].lc) tr[p].lc = ++num;
        Insert(tr[p].lc, l, mid, val, add);
    } else {
        if (!tr[p].rc) tr[p].rc = ++num;
        Insert(tr[p].rc, mid + 1, r, val, add);
    }
    maintain(p);
}

inline int Merge(int p, int q, int l, int r) { ///线段树合并模板
    if (!p) return q;
    if (!q) return p;
    if (l == r) {
        tr[p].maxx = tr[q].maxx + tr[p].maxx;
        tr[p].dat = tr[p].maxx ? l : 0;
        return p;
    }
    int mid = l + ((r - l) >> 1);
    tr[p].lc = Merge(tr[p].lc, tr[q].lc, l, mid);
    tr[p].rc = Merge(tr[p].rc, tr[q].rc, mid + 1, r);
    maintain(p);
    return p;
}
      
///主函数中预处理:
for (int i = 1; i <= n; i++)
   Root[i] = ++num;
                      
///并且主函数中所有x要统计用Root[x]调用!
C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdlib>
#define MAXN 100010
using namespace std;

struct tree {
    int lc, rc, maxx, dat;
} tr[MAXN * 20 * 4];

int n, m, num, root, degree[MAXN];
int Root[MAXN], t, b[MAXN], M;
vector<int> G[MAXN];

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

///lca部分
int d[MAXN], fa[MAXN][20];

inline void lca_dfs(int u, int f) {
    for (int i = 0; i < G[u].size(); i++) {
        int to = G[u][i];
        if (to == f) continue;
        d[to] = d[u] + 1;
        fa[to][0] = u;
        for (int j = 1; j <= t; j++)
            fa[to][j] = fa[fa[to][j - 1]][j - 1];
        lca_dfs(to, u);
    }
}

inline int lca(int x, int y) {
    if (d[x] > d[y]) swap(x, y);
    for (int i = t; i >= 0; i--) {
        if (d[fa[y][i]] >= d[x])
            y = fa[y][i];
    }
    if (x == y) return x;
    for (int i = t; i >= 0; i--) {
        if (fa[x][i] != fa[y][i]) {
            x = fa[x][i];
            y = fa[y][i];
        }
    }
    return fa[x][0];
}

///线段树动态开点部分

inline void maintain(int p) {
    tr[p].maxx = max(tr[tr[p].lc].maxx, tr[tr[p].rc].maxx);
    if (tr[tr[p].lc].maxx > tr[tr[p].rc].maxx)
        tr[p].dat = tr[tr[p].lc].dat;
    else if (tr[tr[p].rc].maxx > tr[tr[p].lc].maxx)
        tr[p].dat = tr[tr[p].rc].dat;
    else
        tr[p].dat = min(tr[tr[p].lc].dat, tr[tr[p].rc].dat);
}


inline void Insert(int p, int l, int r, int val, int add) {
    if (l == r) {
        tr[p].maxx += add;
        tr[p].dat = tr[p].maxx ? l : 0;
        return;
    }
    int mid = l + ((r - l) >> 1);
    if (val <= mid) {
        if (!tr[p].lc) tr[p].lc = ++num;
        Insert(tr[p].lc, l, mid, val, add);
    } else {
        if (!tr[p].rc) tr[p].rc = ++num;
        Insert(tr[p].rc, mid + 1, r, val, add);
    }
    maintain(p);
}

inline int Merge(int p, int q, int l, int r) {
    if (!p) return q;
    if (!q) return p;
    if (l == r) {
        tr[p].maxx = tr[q].maxx + tr[p].maxx;
        tr[p].dat = tr[p].maxx ? l : 0;
        return p;
    }
    int mid = l + ((r - l) >> 1);
    tr[p].lc = Merge(tr[p].lc, tr[q].lc, l, mid);
    tr[p].rc = Merge(tr[p].rc, tr[q].rc, mid + 1, r);
    maintain(p);
    return p;
}

struct node {
    int x, y, z;
} Commands[MAXN];

int Ans[MAXN];

///树上差分部分:
inline void dfs(int u, int fa) {
    for (int i = 0; i < G[u].size(); i++) {
        int to = G[u][i];
        if (to == fa) continue;
        dfs(to, u);
        Root[u] = Merge(Root[u], Root[to], 1, M);
    }
    Ans[u] = tr[Root[u]].dat;
}

int main() {
    n = read(); m = read();
    t = (int)(log(n) / log(2)) + 1;
    for (int i = 1; i < n; i++) {
        int x = read(), y = read();
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        Root[i] = ++num;
    d[1] = 1;
    lca_dfs(1, 0);
    for (int i = 1; i <= m; i++) {
        Commands[i].x = read();
        Commands[i].y = read();
        Commands[i].z = read();
        b[i] = Commands[i].z;
    }
    sort(b + 1, b + 1 + m);
    M = unique(b + 1, b + 1 + m) - (b + 1);
    for (int i = 1; i <= m; i++) {
        int Z = lower_bound(b + 1, b + 1 + M, Commands[i].z) - b;
        int p = lca(Commands[i].x, Commands[i].y);
        Insert(Root[Commands[i].x], 1, M, Z, 1);
        Insert(Root[Commands[i].y], 1, M, Z, 1);
        Insert(Root[p], 1, M, Z, -1);
        if (fa[p][0]) Insert(Root[fa[p][0]], 1, M, Z, -1);
    }
    dfs(1, 0);
    for (int i = 1; i <= n; i++)
        printf("%d\n", b[Ans[i]]);
    return 0;
}

10.P3389 【模板】高斯消元法

有关浮点数的一些小知识点:

1.比较浮点数大小时必须采用a - b > eps, 其中 eps = 1e-5等(浮点数二分常用,但是判断这个浮点数是否为0时就可以不用)

2024.1.6补充:“==”只能判断两个整数是否相等

2.fabs是求浮点数的绝对值的,头文件最好同时加上

3.eps的位数不能小于等于最后答案输出的位数 + 1,例如P1471方差这题,要求最后答案保留四位小数输出,那么eps就至少是1e-6,1e-7更保险一些。

C++
#include <cstdlib>
#include <cmath>
C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#define MAXN 110
#define eps 0.00001
using namespace std;

struct node {
    double b[MAXN][MAXN];
} Martix;

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

int n;
double ans[MAXN];
bool illegal;

inline void Gauss() {
    for (int i = 1; i <= n; i++) {
        int r = i;
        for (int x = i + 1; x <= n; x++) {
            if (fabs(Martix.b[x][i]) > fabs(Martix.b[r][i])) {
                r = x;
            }
        }
        if (fabs(Martix.b[r][i]) < eps) {
        	printf("No Solution\n");
        	illegal = true;
        	return;
		}
        if (r != i) {
            for (int x = 1; x <= n + 1; x++)
                swap(Martix.b[i][x], Martix.b[r][x]);
        }
        double div = Martix.b[i][i];
        for (int x = i; x <= n + 1; x++)
            Martix.b[i][x] /= div;
        for (int x = i + 1; x <= n; x++) {
            div = Martix.b[x][i];
            for (int j = i; j <= n + 1; j++)
                Martix.b[x][j] -= Martix.b[i][j] * div;
        }
    }
    ans[n] = Martix.b[n][n + 1];
    for (int x = n - 1; x >= 1; x--) { ///注:高斯消元中的回带解方程在最后一步才进行,不要将其放置for循环中。 
        ans[x] = Martix.b[x][n + 1];
        for (int j = x + 1; j <= n; j++)
            ans[x] -= Martix.b[x][j] * ans[j];
    } ///高斯消元中的回带相当于已知x[i + 1]~x[n]然后代入第i个方程中反求出x[i]; 
}

int main() {
    n = read();
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n + 1; j++) {
            scanf("%lf", &Martix.b[i][j]);
        }
    }
    Gauss();
    if (!illegal) {
        for (int i = 1; i <= n; i++)
            printf("%.2lf\n", ans[i]);
    }
    return 0;
}

11.P3810 【模板】三维偏序(陌上花开)

有关sort的知识点:

当我们用sort(a + First, a + End); 时

是对[First, END)进行排序;

一定要记住:sort是左闭右开!(实在不行把左右区间都多放一位)

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 100010
#define MAXQ 200010
using namespace std;

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

struct node {
    int a, b, c, tot, ans;
} Flower[MAXN], newFlower[MAXN];
int n, k, eid, top;

inline bool cmp1(const node &x, const node &y) {
    if (x.a != y.a) return x.a < y.a;
    if (x.b != y.b) return x.b < y.b;
    return x.c < y.c;
}

inline bool cmp2(const node &x, const node &y) {
    if (x.b != y.b) return x.b < y.b;
    return x.c < y.c;
}

int C[MAXQ], f[MAXN];

inline int lowbit(int x) {
    return x & (-x);
}

inline void update(int x, int y) {
    for (int i = x; i < k; i += lowbit(i)) {
        C[i] += y;
    }
    return;
}

inline int query(int x) {
    int ans = 0;
    for (int i = x; i; i -= lowbit(i))
        ans += C[i];
    return ans;
}

inline void Cdq(int l, int r) {
    int mid = l + ((r - l) >> 1);
    if (l < mid) Cdq(l, mid);
    if (mid + 1 < r) Cdq(mid + 1, r);
    ///注意sort排序是从[First, end), 左闭右开
    sort(newFlower + l, newFlower + mid + 1, cmp2);
    sort(newFlower + mid + 1, newFlower + r + 1, cmp2);
    int point = l;
    for (int i = mid + 1; i <= r; i++) {
        while (newFlower[i].b >= newFlower[point].b && point <= mid) {
            update(newFlower[point].c, newFlower[point].tot);
            point++;
        }
        newFlower[i].ans += query(newFlower[i].c);
    }
    for (int i = l; i < point; i++) {///Cdq分治后要清空树状数组
		update(newFlower[i].c, -newFlower[i].tot);
	}
}

int main() {
    n = read(); k = read();
    for (int i = 1; i <= n; i++) {
        Flower[i].a = read();
        Flower[i].b = read();
        Flower[i].c = read();
    }
    sort(Flower + 1, Flower + 1 + n, cmp1);
    k++;
    for (int i = 1; i <= n; i++) {
        top++;
        if (Flower[i].a != Flower[i + 1].a || Flower[i].b != Flower[i + 1].b || Flower[i].c != Flower[i + 1].c) {
            newFlower[++eid].a = Flower[i].a;
            newFlower[eid].b = Flower[i].b;
            newFlower[eid].c = Flower[i].c;
            newFlower[eid].tot = top;
            top = 0;
        }
    }
    Cdq(1, eid);
    for (int i = 1; i <= eid; i++)
        f[newFlower[i].ans + newFlower[i].tot - 1] += newFlower[i].tot;
    for (int i = 0; i < n; i++)
        printf("%d\n", f[i]);
    return 0;
}

12.CF1714G Path Prefixes

小技巧:树上二分/链上二分:

∵dfs会遍历一个节点两次,如果我们把正在遍历的节点的序列提出来的话,可以发现这个序列其实是一个stack,深度越深的节点会后进先出。

∴我们可以用一个stack来存储链上信息:

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#define MAXN 200010
using namespace std;

inline long long read() {
	register long long x = 0, f = 1;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (isdigit(ch)) {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * f;
}

long long T, N, Ans[MAXN], A[MAXN];
long long p[MAXN], a[MAXN], b[MAXN], st[MAXN], top;
vector<long long> G[MAXN];

inline void dfs(long long x, long long Fa) {
	for (long long i = 0; i < G[x].size(); i++) {
		long long to = G[x][i];
		if (to == Fa) continue;
		A[to] = a[to] + A[x];
		long long y = st[top];
		st[++top] = y + b[to];
		Ans[to] = upper_bound(st + 1, st + 1 + top, A[to]) - st - 1;
		dfs(to, x);
		top--;
	}
}
///树上二分新方法:用dfs+一个stack/一个手写stack来存储 
///来一个新节点加一个, 
int main() {
	T = read();
	for (long long i = 1; i <= T; i++) {
		N = read();
		for (long long j = 1; j <= N; j++) G[j].clear();
		for (long long j = 2; j <= N; j++) {
			long long fa = read();
			G[fa].push_back(j);
			G[j].push_back(fa);
			a[j] = read(); b[j] = read();
		}
		A[1] = 0;
		dfs(1, 0);
		for (long long j = 2; j <= N; j++)
			printf("%lld ", Ans[j]);
		printf("\n");
	}
	return 0;
}

13.P1197 [JSOI2008] 星球大战

时间倒序方法:将删边->倒序加边,在处理连通性(可以用并查集来维护)的图论问题中可以将问题大大简化

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#define MAXN 400010
using namespace std;

inline int read() {
	register int x = 0, f = 1;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (isdigit(ch)) {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * f;
}

struct edge {
	int x, y;
} E[MAXN];
int n, m, Ans[MAXN];
vector<int> G[MAXN];
int Commands[MAXN], fa[MAXN];
bool Cut[MAXN];

inline int Find_fa(int x) {
	if (fa[x] == x) return x;
	return fa[x] = Find_fa(fa[x]);
}

inline void merge(int x, int y) {
	x = Find_fa(x); y = Find_fa(y);
	if (x == y) return;
	fa[y] = x;
}

inline bool same(int x, int y) {
	x = Find_fa(x); y = Find_fa(y);
	if (x == y) return true;
	return false;
}

int main() {
	n = read(); m = read();
	for (int i = 1; i <= n; i++) fa[i] = i;
	for (int i = 1; i <= m; i++) {
		E[i].x = read();
		E[i].y = read();
		G[E[i].x].push_back(E[i].y);
		G[E[i].y].push_back(E[i].x);
	}
	int k = read();
	for (int i = 1; i <= k; i++) {
		Commands[i] = read();
		Cut[Commands[i]] = true;
	}
	///计算出全部删除之后还有多少个连通块
	int cnt = n - k; ///直接删掉了k个点,其他未删掉的点之间的边还没有连,又是一种将删点/删边转化为加边/加点的倒序操作
	for (int i = 1; i <= m; i++) {
		if (!Cut[E[i].x] && !Cut[E[i].y] && !same(E[i].x, E[i].y)) {
			cnt--;
			merge(E[i].x, E[i].y);
		}
	} 
	Ans[k + 1] = cnt;
   //时间倒序:倒序加边维护连通块个数
	for (int i = k; i >= 1; i--) {
		cnt++;//这个被删掉的点又复活成了一个单独节点的联通块
		Cut[Commands[i]] = false;
		for (int j = 0; j < G[Commands[i]].size(); j++) {
			int to = G[Commands[i]][j];
			if (!Cut[to] && !Cut[Commands[i]] && !same(Commands[i], to)) {
				cnt--;
				merge(Commands[i], to);
			}
		}
		Ans[i] = cnt;
	}
	for (int i = 1; i <= k + 1; i++) 
		printf("%d\n", Ans[i]);
	return 0;
}

14.P1081 [NOIP2012 提高组] 开车旅行

一些容易被毒瘤数据点卡惨但是能过样例的小错误:

e.g

  • 1.多重数组刷表法(01背包等除外)最好按照第一维第二维第三维……的顺序去刷表,否则会出现一些奇奇怪怪的问题调上几天都过不去

  • 2.在赋INF(哨兵)初值的时候,最好远远大于输入值的极值(否则就像这个题目的#12用1e9的INFmultiset就会被卡成RE),切记切记!

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <set>
#define MAXN 100010
#define INF 100000000000
///注意这里的哨兵的初值一定要远远大于h[i]的极值,否则这道题会有一些毒瘤数据点卡multiset成RE 
using namespace std;

typedef pair<long long, long long> Pa; 
inline long long read() {
	register long long x = 0, f = 1;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') f = -1;
		ch = getchar(); 
	}
	while (isdigit(ch)) {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * f;
} 

long long n, h[MAXN], X_0, ga[MAXN], gb[MAXN];
long long m, s[MAXN], X[MAXN];
multiset<Pa> st;
multiset<Pa>::iterator it, it1, it2, it3, it4;

long long f[18][MAXN][2], w;
///f[i][j][k]表示开了2^i天,j点为起点,最先开的是小A(j == 0)\小B(j == 1)到达的地方
long long da[18][MAXN][2], db[18][MAXN][2];

inline void init_f() {
	for (long long i = 1; i <= n; i++) {
		f[0][i][0] = ga[i];
		f[0][i][1] = gb[i]; 
	}
	for (long long i = 1; i <= n; i++) {
		f[1][i][0] = f[0][f[0][i][0]][1];
		f[1][i][1] = f[0][f[0][i][1]][0];
	}
	for (long long j = 2; j < w; j++) {
		for (long long i = 1; i <= n; i++) {
			f[j][i][0] = f[j - 1][f[j - 1][i][0]][0];
			f[j][i][1] = f[j - 1][f[j - 1][i][1]][1];
		}
	}
}

inline void init_d() {
	for (long long i = 1; i <= n; i++) {
		da[0][i][0] = abs(h[ga[i]] - h[i]);
		da[0][i][1] = 0;
		db[0][i][1] = abs(h[gb[i]] - h[i]);
		db[0][i][0] = 0;
	}
	for (long long i = 1; i <= n; i++) {
		da[1][i][0] = da[0][i][0];
		da[1][i][1] = da[0][f[0][i][1]][0];
		db[1][i][0] = db[0][f[0][i][0]][1];
		db[1][i][1] = db[0][i][1];
	}
	for (long long j = 2; j < w; j++) { ///多重数组刷表法最后按照第一位~第二位~的顺序遍历避免出错 
		for (long long i = 1; i <= n; i++) {
			da[j][i][0] = da[j - 1][i][0] + da[j - 1][f[j - 1][i][0]][0];
			da[j][i][1] = da[j - 1][i][1] + da[j - 1][f[j - 1][i][1]][1];
			db[j][i][0] = db[j - 1][i][0] + db[j - 1][f[j - 1][i][0]][0];
			db[j][i][1] = db[j - 1][i][1] + db[j - 1][f[j - 1][i][1]][1];
		}
	}
}

long long cnt1, cnt2, ans1, ans2, maxx;

inline void Calc(int start, int x) {
	ans1 = ans2 = 0;
	int p = start;
	for (long long i = w; i >= 0; i--) {
		if (f[i][p][0] && ans1 + ans2 + da[i][p][0] + db[i][p][0] <= x) {
			ans1 += da[i][p][0];
			ans2 += db[i][p][0];
			p = f[i][p][0];
		} //题目条件:小A先开  
	}
}

inline int Compare(Pa x, Pa y) {
	///相等:-1 左边小:1 右边小:2 
	long long a = x.first, b = x.second;
	long long c = y.first, d = y.second; 
	if (b == 0 && d == 0) return -1;
	if (b == 0) return 2;
	if (d == 0) return 1;
	if (a * d < b * c) return 1;
	if (a * d > b * c) return 2;
	return -1;
}

int main() {
	//freopen("P1081.in", "r", stdin);
	//freopen("P1081.out", "w", stdout);
	n = read();
	w = (long long)(log(n) / log(2));
	for (long long i = 1; i <= n; i++) h[i] = read();
	st.insert(make_pair(INF, 0));
	st.insert(make_pair(-INF, 0));
	st.insert(make_pair(INF, 0));
	st.insert(make_pair(-INF, 0)); //放置两个哨兵,避免第一次it指针会溢出
	for (long long i = n; i; i--) {
		st.insert(make_pair(h[i], i));
		it = st.find(make_pair(h[i], i));
		it1 = ++it; it2 = ++it;
	 	it--; it--;
	 	it3 = --it;
	 	it4 = --it;
	 	int d1, d2, d3, d4;
	 	///it4 < it3 < it1 < it2 
	 	if ((*it3).first == -INF) d3 = INF;
	 	else d3 = h[i] - (*it3).first;
	 	if ((*it1).first == INF) d1 = INF;
	 	else d1 = (*it1).first - h[i];
	 	if ((*it2).first == INF) d2 = INF;
	 	else d2 = (*it2).first - h[i];
	 	if ((*it4).first == -INF) d4 = INF;
	 	else d4 = h[i] - (*it4).first;
	 	if (d1 < d3) {
	 		gb[i] = (*it1).second;
	 		if (d3 <= d2) ga[i] = (*it3).second;
	 		else ga[i] = (*it2).second;
		} else if (d1 > d3) {
			gb[i] = (*it3).second;
			if (d1 < d4) ga[i] = (*it1).second;
			else ga[i] = (*it4).second;
		} else {
			gb[i] = (*it3).second;
			ga[i] = (*it1).second;
		}
	} 
	init_f();
	init_d();
	//Subtask 1: 
	X_0 = read();
	Calc(1, X_0);
	cnt1 = ans1; cnt2 = ans2;
	maxx = 1;
	for (long long i = 2; i <= n; i++) {
		Calc(i, X_0);
		if (Compare(make_pair(cnt1, cnt2), make_pair(ans1, ans2)) == -1) {
			if (h[maxx] < h[i]) {
				maxx = i;
				cnt1 = ans1;
				cnt2 = ans2;
			} 
		} else if (Compare(make_pair(cnt1, cnt2), make_pair(ans1, ans2)) == 2) {
			maxx = i;
			cnt1 = ans1;
			cnt2 = ans2;
		}
	}
	printf("%lld\n", maxx);
	m = read();
	for (long long i = 1; i <= m; i++) {
		s[i] = read(); X[i] = read();
		Calc(s[i], X[i]);
		printf("%lld %lld\n", ans1, ans2);
	} 
	//fclose(stdin);
	//fclose(stdout);
	return 0;
	
}

15. AcWing294. 计算重复

1.遇到一些可以直接排除的情况但是需要在主程序中打多个Flag跳出一层层循环的,可以直接放在一个void函数里面当中比较方便(想直接结束主程序是用exit(0))

2.不知道多少组的字符串输入,用scanf一定要是:

C++
while((scanf("%s %s", str1, st2) == 2)

否则会被卡成TLE

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#define MAXN 110
using namespace std;

char s1[MAXN], s2[MAXN];
long long n1, n2;
long long f[MAXN][40];
//f[i][j]表示从s1(单独一个)的第i个字符开始找出2^j个S2还需要的字符个数的minn

inline void Calc() { ///遇到一些可以直接排除的情况但是需要在主程序中打多个Flag跳出一层层循环的,可以直接放在一个void函数里面当中比较方便 
	memset(f, 0, sizeof(f)); 
	long long len1 = strlen(s1);
	long long len2 = strlen(s2);
	for (long long i = 0; i < len1; i++) {
		f[i][0] = 0;
		long long p = i;
		for (long long j = 0; j < len2; j++) {
			long long cnt = 0;
			while (s1[p] != s2[j]) {
				p = (p + 1) % len1;
				if (++cnt >= len1) {
					printf("0\n");
					return;
				}
			}
			p = (p + 1) % len1;
			f[i][0] += cnt + 1;
		}
	}
	for (long long i = 1; i <= 30; i++) {
		for (long long j = 0; j < len1; j++) {
			f[j][i] = f[j][i - 1] + f[(j + f[j][i - 1]) % len1][i - 1];
		}
	}
	long long maxx = 0;
	for (long long i = 0; i < len1; i++) {
		long long x = i, ans = 0;
		for (long long j = 30; j >= 0; j--) {
			if (x + f[x % len1][j] <= len1 * n1) {
				x += f[x % len1][j];
				ans += 1 << j;
			}
		}
		maxx = max(maxx, ans);
	}
	printf("%lld\n", maxx / n2);
} 

int main() {
	while (cin >> s2 >> n2 >> s1 >> n1) {
		Calc();
	}
	return 0;
} 

16.CF1761C Set Construction

这是2022.11.20 Codeforces Pinely Round 1 的C题,笔者当时没有想出比较好写的构造就去跑路卷王洪凯了,今天到机房问一下学长发现这道题就是一道水题,寄! 自己构造思维还是太逊了!

关于对vector里面元素的排序方式:

C++
vector<int> ans;
sort(ans.begin(), ans.end());

Code:

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#define MAXN 1010
using namespace std;

int t, n;
char str[MAXN];
vector<int> ans[MAXN];

int main() {
	scanf("%d", &t);
	for (int i = 1; i <= t; i++) {
		scanf("%d", &n);
		for (int j = 0; j <= n; j++) ans[j].clear();
		for (int j = 1; j <= n; j++) {
			scanf("%s", str + 1);
			for (int k = 1; k <= n; k++) {
				if (str[k] == '1') {
					ans[k].push_back(j);
				}
			}
			ans[j].push_back(j);
		}
		for (int j = 1; j <= n; j++)
			sort(ans[j].begin(), ans[j].end()); //这是对一个vector里面的元素排序
		for (int j = 1; j <= n; j++) {
			printf("%d ", ans[j].size());
			for (int k = 0; k < ans[j].size(); k++)
				printf("%d ", ans[j][k]);
			printf("\n");
		}
	}
	return 0;
}

17.CF1775C Interesting Sequence

以下内容感谢CCH队长:当我们使用右移计算一个超过int范围的2的次幂时,可以采用

C++
1ll << i;
C++
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAXN 100
using namespace std;

long long t, N, X, a[MAXN], b[MAXN];

inline long long read() {
    long long x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

int main() {
    t = read();
    while (t--) {
        N = read(); X = read();
        if (N == X) printf("%lld\n", N);
        else {
            memset(a, 0, sizeof(a));
            memset(b, 0, sizeof(b));
            long long cnt1 = 0, cnt2 = 0, ans = 0;
            while (N) {
                long long yu = N % 2;
                cnt1++; a[cnt1] = yu;
                N /= 2;
            }
            while (X) {
                long long yu = X % 2;
                cnt2++; b[cnt2] = yu;
                X /= 2;
            }
            if (cnt1 < cnt2) printf("-1\n");
            else if (cnt1 > cnt2) {
                if (b[cnt2] == 0) printf("%lld\n", (1ll << cnt1));
                else printf("-1\n");
            } else {
                bool flag = false;
                for (long long i = cnt1; i >= 1; i--) {
                    if (a[i] == 0 && b[i] == 1) {
                        ans = -1;
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    for (long long i = cnt1; i >= 1; i--) {
                        if (a[i] == 1 && b[i] == 0) {
                            if (a[i + 1] == 1 && b[i + 1] == 1) {
                                ans = -1;
                                flag = true;
                            } else {
                                for (long long j = i - 1; j >= 1; j--) {
                                    if (b[j] == 1) {
                                        ans = -1;
                                        flag = true;
                                    }
                                }
                                if (!flag) {
                                    for (long long j = cnt1; j >= i + 2; j--)
                                        if (a[j] == 1) ans += (1ll << (j - 1));
                                    ans += (1ll << i);
                                }
                            }
                            break;
                        }
                    }
                }
                printf("%lld\n", ans);
            }
        }
    }
    return 0;
}

加训 ICPC 时被阴到了,犯过很多次的错误:

如果一个函数没有返回值,那么一定要设为 void 类型,否则会出现 Undefined Behaviour 从而导致本地 AC 提交 RE!

另外:如果是像本代码一样,将vector中插入临时构建的元素的话(尤其是结构体类型的时候),使用emplace_back会更优。(如果是插入已经存在的元素的话就使用 push_back 即可。)

C++
///警钟敲烂*inf: 没有返回值的函数一定要写成 void 类型,否则会出现 Undefined Behaviour 然后 RE!(这时本地AC)
///另外:如果是像本代码一样,将vector中插入临时构建的元素的话(尤其是结构体类型的时候),使用emplace_back会更优。 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const long long MAXN = 1e6 + 10;
const long long MAXM = 1e6 + 10;

inline long long read() {
	long long x = 0, f = 1;
	char ch = getchar();
	while (!isdigit(ch)) {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (isdigit(ch)) {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * f;
} 

struct node {
	long long to, index;
};

long long n, m, G[MAXM][2], fa[MAXN];
vector<node> G2[MAXN];

long long find(long long x) {
	if (x == fa[x]) return x;
	return fa[x] = find(fa[x]);
}

void unite(long long x, long long y) {
	long long X = find(x);
	long long Y = find(y);
	if (X != Y) fa[X] = Y;
}

long long Start, End;
bool used[MAXM], Used[MAXM];

void dfs(long long u) {
	if (u == End) {
		for (long long i = 1; i <= m; i++)
			Used[i] = used[i];
		return;
	}
	for (long long i = 0; i < G2[u].size(); i++) {
		if (!used[G2[u][i].index]) {
			used[G2[u][i].index] = true;
			dfs(G2[u][i].to);
			used[G2[u][i].index] = false;
		}
	}
}

int main() {
	long long t = read();
	for (long long u = 1; u <= t; u++) {
		n = read(); m = read();
		for (long long i = 1; i <= m; i++) {
			G[i][0] = read();
			G[i][1] = read();	
			used[i] = false;
			Used[i] = false;
		}
		for (long long i = 1; i <= n; i++) {
			fa[i] = i;
			G2[i].clear();
		}
		long long Maxx = -1;
		for (long long i = 1; i <= m; i++) {
			if (find(G[i][0]) == find(G[i][1])) {
				Maxx = i;
				break;
			}
			unite(G[i][0], G[i][1]);
			G2[G[i][0]].emplace_back((node){G[i][1], i});
			G2[G[i][1]].emplace_back((node){G[i][0], i}); 
		} 
		if (Maxx == -1) printf("-1\n");
		else {
			Start = G[Maxx][0], End = G[Maxx][1];
			dfs(Start);
			for (long long i = 1; i < Maxx; i++) {
				if (Used[i]) 
					printf("%d ", i);
			}
			printf("%d\n", Maxx);
		}
	}
	return 0;
}

19.P9883 [EC Final 2021] Fenwick Tree

被运算符优先级坑了一把……题目不难,但要是没注意到运算法优先级问题的话,现场比赛真不清楚要调试多少时间……

加法比按位与优先级高,所以 x + x & (-x) 会被处理成 (x + x) & (-x), …… 警钟敲烂!所以括号是不能偷懒的!

C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

const int MAXN = 1e6 + 10;
int n;
char str[MAXN];
bool used[MAXN];
vector<int> G[MAXN];

void init(int x) {
	if (used[x] || x > n) return;
	used[x] = true;
	if ((x + (x & (-x))) > n) return;
	G[x].push_back(x + (x & (-x)));
	G[x + (x & (-x))].push_back(x);
 	init(x + (x & (-x))); 
} 

int dfs(int u, int fa) {
	if (G[u].size() == 1 && G[u][0] == fa) {
		if (str[u] == '0') return 0;
		return 1;
	}
	int cnt = 0, ans = 0;
	for (auto x:G[u]) {
		if (x == fa) continue;
		ans += dfs(x, u); 
		if (str[x] == '1') cnt++;
	}
	if (cnt == 0) {
		if (str[u] == '0') return ans;
		return ans + 1;
	} else if (cnt == 1) {
		if (str[u] == '0') return ans + 1;
		return ans;
	}
	return ans;
}

int main() {
	int t; scanf("%d", &t);
	for (int u = 1; u <= t; u++) {
		scanf("%d", &n);
		scanf("%s", str + 1); 
		for (int i = 1; i <= n; i++) {
			used[i] = false;
			G[i].clear();
		}
		for (int i = 1; i <= n; i++) {
			if (!used[i]) init(i);
		}
		int Ans = 0;
		for (int i = 1; i <= n; i++) {
			if ((i + (i & (-i))) > n) Ans += dfs(i, 0);
		}
		printf("%d\n", Ans);
	}
	return 0;
} 
原文