Hướng dẫn giải của Quảng cáo


Chỉ dùng lời giải này khi không có ý tưởng, và đừng copy-paste code từ lời giải này. Hãy tôn trọng người ra đề và người viết lời giải.
Nộp một lời giải chính thức trước khi tự giải là một hành động có thể bị ban.

Lưu ý: Các code mẫu dưới đây chỉ mang tính tham khảo và có thể không AC được bài tập này

Code mẫu của flashmt

const maxn=2100;
var n,sm,m:longint;
    a:array[1..maxn,1..maxn] of byte;
    dau:array[1..maxn] of longint;

procedure re;
var i,x,y:longint;
begin
     fillchar(a,sizeof(a),0);
     readln(n,m);
     for i:=1 to m do
     begin
          readln(x,y);
          a[x,y]:=1;
          a[y,x]:=1;
     end;
end;
procedure duyet(x:longint);
var i:longint;
begin
     for i:=1 to n do
         if (dau[i]=0) and (a[x,i]=1) then
         begin
              dau[i]:=sm;
              duyet(i);
         end;
end;

procedure pr;
var i:longint;
begin
     fillchar(dau,sizeof(dau),0);
     sm:=0;
     for i:=1 to n do
         if dau[i]=0 then
         begin
              inc(sm); dau[i]:=sm;
              duyet(i);
         end;
end;

procedure wr;
begin
     write(m-n+sm);
end;
begin
     re;
     pr;
     wr;
end.

Code mẫu của happyboy99x

#include<cstdio>
#include<vector>
#include<queue>
using namespace std;

vector<vector<int> > g;
int n, m;
bool vst[2000];

int main() {
    scanf("%d%d", &n, &m); g.resize(n);
    for(int i = 0; i < m; ++i) {
        int x, y; scanf("%d%d", &x, &y);
        g[--x].push_back(--y);
        g[y].push_back(x);
    }
    int k = 0; //number of connected component
    for(int i = 0; i < n; ++i) if(!vst[i]) {
        ++k; queue<int> qu; qu.push(i);
        while(!qu.empty()) {
            int u = qu.front(); qu.pop();
            for(vector<int>::iterator it = g[u].begin(); it != g[u].end(); ++it) 
                if(!vst[*it]) {
                    vst[*it] = 1;
                    qu.push(*it);
                }
        }
    }
    printf("%d\n", m - n + k);
    return 0;
}

Code mẫu của ladpro98

#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <climits>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cassert>
#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define REP(i, a, b) for(int i = (a); i <=(b); i++)
#define FORD(i, a, b) for(int i = (a); i > (b); i--)
#define REPD(i, a, b) for(int i = (a); i >=(b); i--)
#define SZ(a) (int((a).size()))
#define ALL(a) (a).begin(), (a).end()
#define PB push_back
#define MP make_pair
#define LL long long
#define LD long double
#define II pair<int, int>
#define X first
#define Y second
#define VI vector<int>
const int N = 2200;
using namespace std;

struct dsu {
    int lab[N];
    int root(int u)
        {return lab[u] <= 0 ? u : (lab[u] = root(lab[u]));}
    void join(int u, int v) {
        if (lab[u] > lab[v]) swap(u, v);
        if (lab[u] == lab[v]) lab[u]--;
        lab[v] = u;
    }
} DS;
int n, m;

int main() {
    ios :: sync_with_stdio(0);
    cin >> n >> m;
    int ans = m, u, v;
    FOR(i, 0, m) {
        cin >> u >> v;
        int x = DS.root(u), y = DS.root(v);
        if (x != y) {DS.join(x, y); ans--;};
    }
    cout << ans;
    return 0;
}

Code mẫu của RR

{$R+,Q+}
uses math;
const
  FINP='';
  FOUT='';
  MAXN=2001;
var
  f1,f2:text;
  n,m:longint;
  queue,deg,xet:array[1..MAXN] of longint;
  a:array[1..MAXN,1..MAXN] of longint;
procedure openF;
begin
  assign(f1,FINP); reset(f1);
  assign(f2,FOUT); rewrite(f2);
end;
procedure closeF;
begin
  close(f1); close(f2);
end;
procedure inp;
var
  i,u,v:longint;
begin
  read(f1,n,m);
  for i:=1 to m do
    begin
      read(f1,u,v);
      inc(deg[u]); a[u,deg[u]]:=v;
      inc(deg[v]); a[v,deg[v]]:=u;
    end;
end;
procedure bfs(u:longint);
var
  i,v,first,last:longint;
begin
  first:=1; last:=1; queue[1]:=u; xet[u]:=1;
  while first<=last do
    begin
      u:=queue[first]; inc(first);
      for i:=1 to deg[u] do
        begin
          v:=a[u,i];
          if xet[v]=0 then
            begin xet[v]:=1; inc(last); queue[last]:=v; end;
        end;
    end;
end;
procedure solve;
var
  count,i:longint;
begin
  count:=m;
  for i:=1 to n do
    if xet[i]=0 then
      begin
        inc(count);
        bfs(i);
      end;
  writeln(f2,count-n);
end;
begin
  openF;
  inp;
  solve;
  closeF;
end.

Code mẫu của hieult

#include <set>
#include <map>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <algorithm>

#include <ctime>
#include <deque>
#include <bitset>
#include <cctype>
#include <utility>
#include <cassert>

using namespace std;

typedef long long ll;
typedef double ld;
typedef unsigned int ui;
typedef unsigned long long ull;

#define Rep(i,n) for(int i = 0; i < (n); ++i)
#define Repd(i,n) for(int i = (n)-1; i >= 0; --i)
#define For(i,a,b) for(int i = (a); i <= (b); ++i)
#define Ford(i,a,b) for(int i = (a); i >= (b); --i)
#define Fit(i,v) for(__typeof((v).begin()) i = (v).begin(); i != (v).end(); ++i)
#define Fitd(i,v) for(__typeof((v).rbegin()) i = (v).rbegin(); i != (v).rend(); ++i)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define sz(a) ((int)(a).size())
#define all(a) (a).begin(), (a).end()
#define ms(a,x) memset(a, x, sizeof(a))

template<class F, class T> T convert(F a, int p = -1) { stringstream ss; if (p >= 0) ss << fixed << setprecision(p); ss << a; T r; ss >> r; return r; }
template<class T> T gcd(T a, T b) { T r; while (b != 0) { r = a % b; a = b; b = r; } return a; }
template<class T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template<class T> T sqr(T x) { return x * x; }
template<class T> T cube(T x) { return x * x * x; }
template<class T> int getbit(T s, int i) { return (s >> i) & 1; }
template<class T> T onbit(T s, int i) { return s | (T(1) << i); }
template<class T> T offbit(T s, int i) { return s & (~(T(1) << i)); }
template<class T> int cntbit(T s) { return s == 0 ? 0 : cntbit(s >> 1) + (s & 1); }

const int bfsz = 1 << 16;
char bf[bfsz + 5];
int rsz = 0;
int ptr = 0;
char gc() {
    if (rsz <= 0) {
        ptr = 0;
        rsz = (int) fread(bf, 1, bfsz, stdin);
        if (rsz <= 0)
            return EOF;
    }
    --rsz;
    return bf[ptr++];
}
void ga(char &c) {
    c = EOF;
    while (!isalpha(c))
        c = gc();
}
int gs(char s[]) {
    int l = 0;
    char c = gc();
    while (isspace(c))
        c = gc();
    while (c != EOF && !isspace(c)) {
        s[l++] = c;
        c = gc();
    }
    s[l] = '\0';
    return l;
}
template<class T> bool gi(T &v) {
    v = 0;
    char c = gc();
    while (c != EOF && c != '-' && !isdigit(c))
        c = gc();
    if (c == EOF)
        return false;
    bool neg = c == '-';
    if (neg)
        c = gc();
    while (isdigit(c)) {
        v = v * 10 + c - '0';
        c = gc();
    }
    if (neg)
        v = -v;
    return true;
}

typedef pair<int, int> II;

const ld PI = acos(-1.0);
const ld eps = 1e-9;

const int dr[] = {0, +1, 0, -1};
const int dc[] = {+1, 0, -1, 0};

const int inf = (int)1e9 + 5;
const ll linf = (ll)1e16 + 5;
const ll mod = (ll)1e9 + 7;

#define maxn 10005

int n, m;
int adj[maxn], last[maxn], next[maxn], E, flag[maxn];

void add(int u, int v){
    adj[E] = v; next[E] = last[u]; last[u] = E++;
    adj[E] = u; next[E] = last[v]; last[v] = E++;
}

void go(int u){
    flag[u] = 1;
    for(int e = last[u]; e != -1; e = next[e]){
        int v = adj[e];
        if(!flag[v]) go(v);
    }
}

int  main()
{
//  freopen("in.txt", "r", stdin);

    cin >> n >> m;
    ms(last, -1);
    E = 0;
    int u, v;

    Rep(run, m){
        cin >> u >> v;
        add(u, v);
    }
    ms(flag, 0);
    int num = 0;
    For(i, 1, n) if(!flag[i]){
        num++; go(i);
    }

    cout << m + num - n << endl;

    return 0;
}

Code mẫu của ll931110

{$MODE DELPHI}
Program ADS;
Const
  input  = '';
  output = '';
  maxn = 20000;
  maxm = 50000;
Var
  free: array[1..maxn] of boolean;
  adj,x,y: array[1..maxm] of integer;
  h: array[1..maxn + 1] of integer;
  n,m: integer;

Procedure LoadGraph;
Var
  f: text;
  i: integer;
Begin
  Fillchar(h, sizeof(h), 0);
  Assign(f, input);
    Reset(f);

    Readln(f, n, m);
    For i:= 1 to m do
      Begin
        Readln(f, x[i], y[i]);
        inc(h[x[i]]);
        inc(h[y[i]]);
      End;
  Close(f);

  For i:= 2 to n do h[i]:= h[i] + h[i - 1];
  For i:= 1 to m do
    Begin
      adj[h[x[i]]]:= y[i];
      dec(h[x[i]]);
      adj[h[y[i]]]:= x[i];
      dec(h[y[i]]);
    End;
  h[n + 1]:= 2 * m;
End;

Procedure DFS(u: integer);
Var
  iv,v: integer;
Begin
  For iv:= h[u] + 1 to h[u + 1] do
    Begin
      v:= adj[iv];
      If free[v] then
        Begin
          free[v]:= false;
          DFS(v);
        End;
    End;
End;

Procedure solve;
Var
  f: text;
  i,cnt: integer;
Begin
  cnt:= 0;
  Fillchar(free, sizeof(free), true);
  For i:= 1 to n do if free[i] then
    Begin
      inc(cnt);
      free[i]:= false;
      DFS(i);
    End;

  Assign(f, output);
    Rewrite(f);
    Writeln(f, m - n + cnt);
  Close(f);
End;

Begin
  LoadGraph;
  solve;
End.

Code mẫu của khuc_tuan

//{$APPTYPE CONSOLE}
 {$mode delphi}

uses math, sysutils;

type
    Node = class
        i : integer;
        n : Node;
    end;

var
    ke : array[1..2000] of Node;
    res, m, i, u, v, n : integer;
    vs : array[1..2000] of boolean;

procedure AddList(var n : Node; u : integer);
var
    p : Node;
begin
    p := Node.Create;
    p.i := u;
    p.n := n;
    n := p;
end;

procedure dfs(i, tr : integer);
var
    p : Node;
    j : integer;
begin
    vs[i] := true;
    p := ke[i];
    while p<>nil do
    begin
        j := p.i;
        if not vs[j] then dfs(j, i)
        else if j <> tr then inc(res);
        p := p.n;
    end;
end;

begin
    readln(n,m);
    for i:=1 to m do
    begin
        readln(u,v);
        addList(ke[u], v);
        addList(ke[v], u);
    end;
    for i:=1 to n do
        if not vs[i] then
        begin
            dfs(i, -1);
        end;
    writeln(res div 2);
end.

Bình luận

Hãy đọc nội quy trước khi bình luận.



  • 2
    RussVN123  đã bình luận lúc 16, Tháng 5, 2025, 7:11 sửa 3

    Suy nghĩ của mình về lý do có công thức m-n+k:

    • Trước hết thì m-n+k này chính là số cung ngược của đồ thị đã được định chiều .
    • Vì :
    • ** Trước tiên xét đồ thị liên thông đi . Ta thấy nếu nó là cây thì m=n-1 , ta lấy m-n thì ra -1 . Mà cơ sở thì số cung ngược là 0 nên ta sẽ +1 vào để tạo công thức .
    • Như vậy ta có trường hợp cây là m-n+1 = 0
    • Giờ nếu thêm 1 cạnh vào cây này thì nó chính là cung ngược , tương tự thêm n cạnh vào thì ta có n cung ngược !
    • Giờ xét lại cây , ta có m0-n+1=0 . Ta thêm x cạnh vào thì ta có m0-n+1+x=x -> m-n+1 = x
    • Vậy nếu có nhiều thành phần liên thông thì sao? Thì nó chính là tổng của các m-n+1 mỗi cây chứ gì nữa !!
    • Hay ta có : m1-n1+1 + m2-n2+1 +...mx-nx+1 và m1+m2+...mx=m và n1+n2+...nx =n do đó ta biến đổi được thành m-n+k . **
    • Vậy tại sao số cung ngược lại là đáp án bài toán ? Ta biết rằng một chu trình trong đồ thị cần ít nhất một cung ngược !
    • Và dựa theo đề bài thì ta thấy mỗi chu trình phải có ít nhất 1 cạnh chưa dùng . Giờ xem đồ thị đã định chiều đi , dễ thấy nếu dùng 1 cung ngược cho chu trình này thì các chu trình sau chắc chắc sẽ không dùng được cung ngược đó luôn ! Hay chính xác mỗi cung ngược chỉ dùng được 1 lần duy nhất !!
    • Mà mỗi cung ngược có thể ghép với một đoạn các cạnh của cây để tạo ra chu trình . Nên ta tham lam bằng cách tạo ra các chu trình chỉ với 1 cung ngược duy nhất
    • Nếu tạo với 2 cung ngược thì sao? Thì ta sẽ lỗ 1 chu trình rồi vì nó có thể tạo ra 2 mà kaka . ( lưu ý là đồ thị ở đây là đồ thị vô hướng )