ホームページ  >  記事  >  バックエンド開発  >  i の最大値を求める C++ プログラム

i の最大値を求める C++ プログラム

PHPz
PHPz転載
2023-09-15 20:09:08998ブラウズ

i の最大値を求める C++ プログラム

整数シーケンス 'seq' と、整数 0 ~ n - 1 を含むサイズ m の整数ペアの配列 'pairs' があるとします。ここで、seq[i] = i (0 ≤ i

  • 整数 j (0

操作を複数回実行した後、seq[i] = i となる i の最大値を見つける必要があります。

入力が n = 4、m = 2、seq = {0, 3, 2, 1}、pairs = {{0, 1}, {2, 3}} の場合、出力は2になります。

可能な最大値は 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

理解を深めるために、以下の実装を見てみましょう −

#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
#define N 100
int tp[N];
vector<int> 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<pair<int, int>> 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<pair<int,int>> pairs = {{0, 1}, {2, 3}};
   solve(n, m, seq, pairs);
   return 0;
}

Input

4, 2, {0, 3, 2, 1}, {{0, 1}, {2, 3}}

出力

2

以上がi の最大値を求める C++ プログラムの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。