旅行计划 记忆化搜索

题目描述

小明要去一个国家旅游。这个国家有#NNN个城市,编号为111至NNN,并且有MMM条道路连接着,小明准备从其中一个城市出发,并只往东走到城市i停止。

所以他就需要选择最先到达的城市,并制定一条路线以城市i为终点,使得线路上除了第一个城市,每个城市都在路线前一个城市东面,并且满足这个前提下还希望游览的城市尽量多。

现在,你只知道每一条道路所连接的两个城市的相对位置关系,但并不知道所有城市具体的位置。现在对于所有的i,都需要你为小明制定一条路线,并求出以城市iii为终点最多能够游览多少个城市。

输入输出格式

输入格式:

111行为两个正整数N,MN, MN,M。

接下来MMM行,每行两个正整数x,yx, yx,y,表示了有一条连接城市xxx与城市yyy的道路,保证了城市xxx在城市yyy西面。

输出格式:

NNN行,第iii行包含一个正整数,表示以第iii个城市为终点最多能游览多少个城市。

输入输出样例

输入样例#1: 复制
5 6
1 2
1 3
2 3
2 4
3 4
2 5
输出样例#1: 复制
1
2
3
4
3

说明

均选择从城市1出发可以得到以上答案。

对于20%20\%20%的数据,N≤100N ≤ 100N100;

对于60%60\%60%的数据,N≤1000N ≤ 1000N1000;

对于100%100\%100%的数据,N≤100000,M≤200000N ≤ 100000,M ≤ 200000N100000,M200000。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
//#include<cctype>
//#pragma GCC optimize(2)
using namespace std;
#define maxn 200005
#define inf 0x7fffffff
//#define INF 1e18
#define rdint(x) scanf("%d",&x)
#define rdllt(x) scanf("%lld",&x)
#define rdult(x) scanf("%lu",&x)
#define rdlf(x) scanf("%lf",&x)
#define rdstr(x) scanf("%s",x)
typedef long long  ll;
typedef unsigned long long ull;
typedef unsigned int U;
#define ms(x) memset((x),0,sizeof(x))
const long long int mod = 1e9 + 7;
#define Mod 1000000000
#define sq(x) (x)*(x)
#define eps 1e-4
typedef pair<int, int> pii;
#define pi acos(-1.0)
//const int N = 1005;
#define REP(i,n) for(int i=0;i<(n);i++)
typedef pair<int, int> pii;
inline ll rd() {
	ll x = 0;
	char c = getchar();
	bool f = false;
	while (!isdigit(c)) {
		if (c == '-') f = true;
		c = getchar();
	}
	while (isdigit(c)) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return f ? -x : x;
}

ll gcd(ll a, ll b) {
	return b == 0 ? a : gcd(b, a%b);
}
int sqr(int x) { return x * x; }


/*ll ans;
ll exgcd(ll a, ll b, ll &x, ll &y) {
	if (!b) {
		x = 1; y = 0; return a;
	}
	ans = exgcd(b, a%b, x, y);
	ll t = x; x = y; y = t - a / b * y;
	return ans;
}
*/

vector<int>vc[maxn];
int n, m;
int d[maxn];
int dfs(int x) {
	if (d[x] != -1)return d[x];
	d[x] = 1;
	for (int i = 0; i < vc[x].size(); i++) {
		int to = vc[x][i];
		d[x] = max(d[x], dfs(to) + 1);
	}
	return d[x];
}

int main() {
	//ios::sync_with_stdio(0);
	memset(d, -1, sizeof(d));
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int u, v;
		rdint(u); rdint(v);
		vc[v].push_back(u);
	}
	for (int i = 1; i <= n; i++) {
		cout << dfs(i) << endl;
	}
	return 0;
}
EPFL - Fighting
原文地址:https://www.cnblogs.com/zxyqzy/p/10284548.html