其他分享
首页 > 其他分享> > 2022HDU多校第十场 - 1002 Photos

2022HDU多校第十场 - 1002 Photos

作者:互联网

DP+ 矩阵快速幂优化转移

Problem - 7245 (hdu.edu.cn)

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> PII;
const int mod = 998244353;
struct matrix
{
    int a[2][2];
    matrix()
    {
        memset(a, 0, sizeof(a));
    }
};
matrix operator*(matrix a, matrix b)
{
    matrix ans;
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            for (int k = 0; k < 2; k++)
                ans.a[i][j] = (ans.a[i][j] + 1ll * a.a[i][k] * b.a[k][j] % mod) % mod;
    return ans;
}
matrix power(matrix a, long long x)
{
    matrix ans;
    ans.a[0][0] = ans.a[1][1] = 1;
    while (x)
    {
        if (x & 1)
            ans = ans * a;
        a = a * a;
        x >>= 1;
    }
    return ans;
}
vector<PII> merge(vector<PII> &ban)
{
	vector<PII> ans;
	int l = -1, r = 0;
	for (auto i : ban)
	{
		if (i.first > r)
		{
			if (l != -1)
				ans.emplace_back(l, r);
			l = i.first;
			r = i.second;
		}
		else
			r = max(r, i.second);
	}
	if (l != -1)
		ans.emplace_back(l, r);
	return ans;
}
int main()
{
	int T;
	scanf("%d", &T);
	matrix all, part;
	all.a[0][0] = all.a[0][1] = all.a[1][0] = 1;
    all.a[1][1] = 2;
    part.a[0][0] = part.a[0][1] = 0;
    part.a[1][0] = 1;
    part.a[1][1] = 2;
	while(T--)
	{
		int n, m;
		scanf("%d%d", &n, &m);
		vector<PII> ban;
		for (int i = 1, x, y; i <= m; i++)
		{
			scanf("%d%d", &x, &y);
			if (x > y) swap(x, y);
			ban.emplace_back(x, y - 1);
		}
		sort(ban.begin(), ban.end());
		ban = merge(ban);
		ban.emplace_back(n + 1, n + 1);

		matrix ans;
		ans.a[0][0] = ans.a[1][1] = 1;
		int last = 0;
		for (auto i : ban)
		{
			int len = i.first - last - 1;
			if (last && len)
				ans = ans * part * power(all, len - 1);
			else if (len)  
				ans = ans * power(all, len);
			last = i.second;
		}
		printf("%d\n", (ans.a[0][0] + ans.a[1][0]) % mod);
	}
	return 0;
}

标签:matrix,2022HDU,len,Photos,int,part,ans,ban,1002
来源: https://www.cnblogs.com/hzy717zsy/p/16694258.html