【动态规划】P9980 [USACO23DEC] Flight Routes G|普及+

本文涉及知识点

C++动态规划

P9980 [USACO23DEC] Flight Routes G

题目描述

Bessie 最近发现她最喜欢的摇滚艺术家 Elsie Swift 正在表演她最新的"时代之旅"音乐会!不幸的是,票卖光的太快了,所以 Bessie 考虑飞往另一个城市参加音乐会。"时代之旅"将在编号为 1 ... N 1\dots N 1...N 的 N N N( 2 ≤ N ≤ 750 2 \le N \le 750 2≤N≤750)座城市上演,每对满足 i < j i<j i<j 的城市对 ( i , j ) (i,j) (i,j) 都可能存在从 i i i 到 j j j 的一条单向直飞航班

从城市 a a a 到城市 b b b 的一条航线 是一个包含 k ≥ 2 k\ge 2 k≥2 座城市的序列 a = c 1 < c 2 < ⋯ < c k = b a=c_1<c_2<\cdots<c_k=b a=c1<c2<⋯<ck=b,使得对于所有的 1 ≤ i < k 1\le i< k 1≤i<k,城市 c i c_{i} ci 到城市 c i + 1 c_{i+1} ci+1 有单向直飞航班 。对于所有满足 i < j i<j i<j 的城市对 ( i , j ) (i,j) (i,j),你将被告知它们之间航线数目的奇偶性( 0 0 0 代表偶数, 1 1 1 代表奇数)。

在计划她的旅行行程时,Bessie 分心了。现在她想知道,有多少对城市间有单向直飞航班。可以证明答案是唯一的。

输入格式

第一行包含整数 N N N。

接下来 N − 1 N-1 N−1 行,第 i i i 行包含 N − i N-i N−i 个整数。第 i i i 行的第 j j j 个整数表示从城市 i i i 到城市 i + j i+j i+j 的航线数目的奇偶性。

输出格式

输出有单向直飞航班的城市对数。

输入输出样例 #1

输入 #1

复制代码
3
11
1

输出 #1

复制代码
2

输入输出样例 #2

输入 #2

复制代码
5
1111
101
01
1

输出 #2

复制代码
6

说明/提示

样例解释 1

有两条单向直飞航班: 1 → 2 1\rightarrow 2 1→2 和 2 → 3 2\rightarrow 3 2→3。有城市 1 , 2 1,2 1,2 之间、 2 , 3 2,3 2,3 之间,仅包含一条单向直飞航班的航线各一条。还有城市 1 , 3 1,3 1,3 之间的航线一条( 1 → 2 → 3 1\rightarrow 2\rightarrow 3 1→2→3)。

样例解释 2

有六条单向直飞航班: 1 → 2 1\rightarrow 2 1→2, 1 → 4 1 \rightarrow 4 1→4, 1 → 5 1\rightarrow 5 1→5, 2 → 3 2\rightarrow 3 2→3, 3 → 5 3\rightarrow 5 3→5, 4 → 5 4\rightarrow 5 4→5。这导致的航线数如下表所示:

出发地\目的地 1 2 3 4 5
1 0 1 1 1 3
2 0 0 1 0 1
3 0 0 0 0 1
4 0 0 0 0 1
5 0 0 0 0 0

这与输入是相符的。

测试点性质

  • 测试点 3 − 4 3-4 3−4 满足 N ≤ 6 N \le 6 N≤6。
  • 测试点 5 − 12 5-12 5−12 满足 N ≤ 100 N \le 100 N≤100。
  • 测试点 13 − 22 13-22 13−22 没有额外限制。

动态规划

奇偶性就是 m o d    2 \mod 2 mod2,乘法可以用位与代替,加法可以用异或代替。

令输入的二维数组是grid。

cnt[i][j]表示 i → j 航线数量的奇偶性 i \rightarrow j航线数量的奇偶性 i→j航线数量的奇偶性
∀ i , j c n t [ i ] [ i + 1 + j ] = g r i d [ i ] [ j ] \forall i,j cnt[i][i+1+j]=grid[i][j] ∀i,jcnt[i][i+1+j]=grid[i][j]

动态规划的状态表示

dp[i][j] i → j i \rightarrow j i→j 直达 航线数量的奇偶性。空间复杂度:O(nn)

动态规划的填表顺序

枚举后继状态,i 从头N-1到0,可以保证无后效性。枚举j的顺序任意。

动态规格的转移方程

直达航线=航线-非直达航线。

枚举非直达航线的倒数第二站k。
∑ k : i + 1 j − 1 c n t [ i ] [ k ] ∗ d p [ k ] [ j ] \sum_{k:i+1}^{j-1}cnt[i][k]*dp[k][j] ∑k:i+1j−1cnt[i][k]∗dp[k][j]

动态规划的初始值

全为0。

动态规划的返回值

dp中1的数量。

代码

核心代码

cpp 复制代码
#include <iostream>
#include <sstream>
#include <vector>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<string>
#include<algorithm>
#include<functional>
#include<queue>
#include <stack>
#include<iomanip>
#include<numeric>
#include <math.h>
#include <climits>
#include<assert.h>
#include<cstring>
#include<list>
#include<array>

#include <bitset>
using namespace std;

template<class T1, class T2>
std::istream& operator >> (std::istream& in, pair<T1, T2>& pr) {
	in >> pr.first >> pr.second;
	return in;
}

template<class T1, class T2, class T3 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t);
	return in;
}

template<class T1, class T2, class T3, class T4 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t);
	return in;
}

template<class T1, class T2, class T3, class T4, class T5, class T6, class T7 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4,T5,T6,T7>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t) >> get<4>(t) >> get<5>(t) >> get<6>(t);
	return in;
}

template<class T = int>
vector<T> Read() {
	int n;
	cin >> n;
	vector<T> ret(n);
	for (int i = 0; i < n; i++) {
		cin >> ret[i];
	}
	return ret;
}
template<class T = int>
vector<T> ReadNotNum() {
	vector<T> ret;
	T tmp;
	while (cin >> tmp) {
		ret.emplace_back(tmp);
		if ('\n' == cin.get()) { break; }
	}
	return ret;
}

template<class T = int>
vector<T> Read(int n) {
	vector<T> ret(n);
	for (int i = 0; i < n; i++) {
		cin >> ret[i];
	}
	return ret;
}

template<int N = 1'000'000>
class COutBuff
{
public:
	COutBuff() {
		m_p = puffer;
	}
	template<class T>
	void write(T x) {
		int num[28], sp = 0;
		if (x < 0)
			*m_p++ = '-', x = -x;

		if (!x)
			*m_p++ = 48;

		while (x)
			num[++sp] = x % 10, x /= 10;

		while (sp)
			*m_p++ = num[sp--] + 48;
		AuotToFile();
	}
	void writestr(const char* sz) {
		strcpy(m_p, sz);
		m_p += strlen(sz);
		AuotToFile();
	}
	inline void write(char ch)
	{
		*m_p++ = ch;
		AuotToFile();
	}
	inline void ToFile() {
		fwrite(puffer, 1, m_p - puffer, stdout);
		m_p = puffer;
	}
	~COutBuff() {
		ToFile();
	}
private:
	inline void AuotToFile() {
		if (m_p - puffer > N - 100) {
			ToFile();
		}
	}
	char  puffer[N], * m_p;
};

template<int N = 1'000'000>
class CInBuff
{
public:
	inline CInBuff() {}
	inline CInBuff<N>& operator>>(char& ch) {
		FileToBuf();
		while (('\r' == *S) || ('\n' == *S) || (' ' == *S)) { S++; }//忽略空格和回车
		ch = *S++;
		return *this;
	}
	inline CInBuff<N>& operator>>(int& val) {
		FileToBuf();
		int x(0), f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行		
		return *this;
	}
	inline CInBuff& operator>>(long long& val) {
		FileToBuf();
		long long x(0); int f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行
		return *this;
	}
	template<class T1, class T2>
	inline CInBuff& operator>>(pair<T1, T2>& val) {
		*this >> val.first >> val.second;
		return *this;
	}
	template<class T1, class T2, class T3>
	inline CInBuff& operator>>(tuple<T1, T2, T3>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val);
		return *this;
	}
	template<class T1, class T2, class T3, class T4>
	inline CInBuff& operator>>(tuple<T1, T2, T3, T4>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val) >> get<3>(val);
		return *this;
	}
	template<class T = int>
	inline CInBuff& operator>>(vector<T>& val) {
		int n;
		*this >> n;
		val.resize(n);
		for (int i = 0; i < n; i++) {
			*this >> val[i];
		}
		return *this;
	}
	template<class T = int>
	vector<T> Read(int n) {
		vector<T> ret(n);
		for (int i = 0; i < n; i++) {
			*this >> ret[i];
		}
		return ret;
	}
	template<class T = int>
	vector<T> Read() {
		vector<T> ret;
		*this >> ret;
		return ret;
	}
private:
	inline void FileToBuf() {
		const int canRead = m_iWritePos - (S - buffer);
		if (canRead >= 100) { return; }
		if (m_bFinish) { return; }
		for (int i = 0; i < canRead; i++)
		{
			buffer[i] = S[i];//memcpy出错			
		}
		m_iWritePos = canRead;
		buffer[m_iWritePos] = 0;
		S = buffer;
		int readCnt = fread(buffer + m_iWritePos, 1, N - m_iWritePos, stdin);
		if (readCnt <= 0) { m_bFinish = true; return; }
		m_iWritePos += readCnt;
		buffer[m_iWritePos] = 0;
		S = buffer;
	}
	int m_iWritePos = 0; bool m_bFinish = false;
	char buffer[N + 10], * S = buffer;
};

class Solution {
public:
	int Ans(vector<vector<char>>& grid) {
		const int N = grid.size() + 1;
		vector<vector<int>> dp(N, vector<int>(N));
		auto cnt = dp;
		for (int i = 0; i + 1 < N; i++) {
			for (int j = 0; j < grid[i].size(); j++) {
				cnt[i][i + 1 + j] = ('1' == grid[i][j]);
			}
		}
		int ans = 0;
		for (int i = N - 1; i >= 0; i--) {
			for (int j = i + 1; j < N; j++) {
				int sum = 0;
				for (int k = i + 1; k < j; k++) {
					sum = sum ^ (cnt[i][k] & dp[k][j]);//位与代替乘法,^代替加法
				}
				dp[i][j] = cnt[i][j] ^ sum;//异或代替减法
				ans += dp[i][j];
			}
		}
		return ans;
	}
};

int main() {
#ifdef _DEBUG
	freopen("a.in", "r", stdin);
#endif // DEBUG	
	ios::sync_with_stdio(0); cin.tie(nullptr);
	//CInBuff<> in; COutBuff<10'000'000> ob;
	int N;
	cin >>N ;
	vector<vector<char>> grid(N - 1);
	for (int i = 0; i + 1 < N; i++)
	{
		grid[i] = Read<char>(N - 1 - i);
	}
#ifdef _DEBUG	
		//printf("K=%d", K);
		Out(grid, ",grid=");
		//Out(que, ",que=");
		//Out(str2, ",str2=");
		//Out(que, ",ope=");
#endif // DEBUG		
		auto res = Solution().Ans(grid);
		cout << res << "\n";

	return 0;
};

单元测试

cpp 复制代码
vector<vector<char>> grid;
		TEST_METHOD(TestMlethod11)
		{
			grid = { {'1','1'},{'1'} };
			auto res = Solution().Ans(grid);
			AssertEx(2, res);
		}
		TEST_METHOD(TestMethod12)
		{
			grid = { {'1','1','1','1'},{'1','0','1'},{'0','1'},{'1'} };
			auto res = Solution().Ans(grid);
			AssertEx(6, res);
		}

扩展阅读

我想对大家说的话
工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。
学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作
有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注
闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。
如果程序是一条龙,那算法就是他的是睛
失败+反思=成功 成功+反思=成功

视频课程

先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
https://edu.csdn.net/course/detail/38771

如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.csdn.net/lecturer/6176

测试环境

操作系统:win7 开发环境: VS2019 C++17

或者 操作系统:win10 开发环境: VS2022 C++17

如无特殊说明,本算法 用**C++**实现。

相关推荐
one____dream2 小时前
【算法】大整数数组连续进位
python·算法
one____dream2 小时前
【算法】合并两个有序链表
数据结构·python·算法·链表
大江东去浪淘尽千古风流人物2 小时前
【Project Aria】Meta新一代的AR眼镜及其数据集
人工智能·嵌入式硬件·算法·性能优化·ar·dsp开发
电饭叔2 小时前
has_solution = False 是什么 费马大定律代码化和定理《计算机科学中的数学》外扩学习3
学习·算法
一只小bit2 小时前
Qt 网络:包含Udp、Tcp、Http三种协议的客户端实践手册
前端·c++·qt·页面
jojo_zjx2 小时前
GESP 23年6月2级 找素数
c++
We་ct2 小时前
LeetCode 238. 除了自身以外数组的乘积|最优解详解(O(n)时间+O(1)空间)
前端·算法·leetcode·typescript
kimicsdn2 小时前
opentelemetry-demo currency cpp 项目编译流程分享
c++·cmake·libprotobuf-dev
Σίσυφος19002 小时前
视觉矩阵之 正交矩阵
人工智能·算法·矩阵