
假设我们有一个整数排列 'seq' 和一个大小为 m 的整数对数组 'pairs',其中包含整数 0 到 n - 1。现在,我们尽可能多地对 seq 执行以下操作,以使 seq[i] = i (0 ≤ i
我们必须选择一个整数 j,其中 0
我们必须找出 i 的最大值,使得在多次执行操作后 seq[i] = i。
因此,如果输入是 n = 4,m = 2,seq = {0, 3, 2, 1},pairs = {{0, 1}, {2, 3}},那么输出将是 2。
立即学习“C++免费学习笔记(深入)”;
易通(企业网站管理系统)是一款小巧,高效,人性化的企业建站程序.易通企业网站程序是国内首款免费提供模板的企业网站系统.§ 简约的界面及小巧的体积:后台菜单完全可以修改成自己最需要最高效的形式;大部分操作都集中在下拉列表框中,以节省更多版面来显示更有价值的数据;数据的显示以Javascript数组类型来输出,减少数据的传输量,加快传输速度。 § 灵活的模板标签及模
最大可能的值是 2。
为了解决这个问题,我们将按照以下步骤进行:
N := 100
Define an array tp of size: N.
Define arrays vtmp, vis of size N.
Define a function dfs(), this will take j, k,
tp[j] := k
insert j at the end of vtmp[k]
for each value b in vis[j], do:
if tp[b] is not equal to 0, then:
Ignore following part, skip to the next iteration
dfs(b, k)
res := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
if seq[i] is same as i, then:
(increase res by 1)
for initialize i := 0, when i < m, update (increase i by 1), do:
a := first value of pairs[i]
b := second value of pairs[i]
insert b at the end of vis[a]
insert a at the end of vis[b]
idx := 1
for initialize i := 0, when i < n, update (increase i by 1), do:
if tp[i] is same as 0, then:
dfs(i, idx)
for each element j in vtmp[idx], do:
if tp[seq[j]] is same as idx and seq[j] is not equal to j, then:
(increase res by 1)
(increase idx by 1)
print(res)Example
让我们看下面的实现以更好地理解−
#includeusing namespace std; const int INF = 1e9; #define N 100 int tp[N]; vector vtmp[N], vis[N]; void dfs(int j, int k){ tp[j] = k; vtmp[k].push_back(j); for(auto b : vis[j]) { if(tp[b] != 0) continue; dfs(b, k); } } void solve(int n, int m, int seq[], vector > pairs) { int res = 0; for(int i = 0; i < n; i++){ if(seq[i] == i) res++; } for(int i = 0; i < m; i++){ int a = pairs[i].first; int b = pairs[i].second; vis[a].push_back(b); vis[b].push_back(a); } int idx = 1; for(int i = 0; i < n; i++) { if(tp[i] == 0) { dfs(i, idx); for(auto j: vtmp[idx]){ if(tp[seq[j]] == idx && seq[j] != j) res++; } idx++; } } cout<< res; } int main() { int n = 4, m = 2, seq[] = {0, 3, 2, 1}; vector > pairs = {{0, 1}, {2, 3}}; solve(n, m, seq, pairs); return 0; }
输入
4, 2, {0, 3, 2, 1}, {{0, 1}, {2, 3}}输出
2










