Codeforces Round #692(div2) C. Peaceful Rooks

(Thinking + Graph Theory)

C. Peaceful Rooks

Question portal:

C. Peaceful Rooks

Main idea:

Give you an n*n chessboard, with m pieces (m<n), each piece is in a different row and column. Each piece can be moved horizontally and vertically. Ask the minimum number of moves to make each piece on the main diagonal of the board.

Ideas:

If it is a point that is already on the diagonal, then naturally there is no need to move, otherwise the number of operations is wasted.
Then the points not on the diagonal must be operated once, move vertically or horizontally to the diagonal.
But we also found that there may be n points forming a ring, just like Example 3. At this time, we can move one of the points to an empty row or column, and then move the remaining n-1 points to the diagonal, and then move the original point back to the diagonal . So when n points are enough to form a ring, their contribution is n+1. At this point, this topic has been transformed into a graph theory problem.

AC Code

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
vector<int>g[N];
int vis[N];
int dfs(int x,int fa)
{
    
    
    vis[x]=1;
    for(int i=0;i<g[x].size();i++)
    {
    
    
        if(g[x][i]==fa) continue;
        if(vis[g[x][i]]==1) return 1;
        dfs(g[x][i],x);
    }
    return 0;
}
int main()
{
    
    
    int t;
    scanf("%d",&t);
    while(t--)
    {
    
    
        int n,m;
        scanf("%d%d",&n,&m);
        int ans=0;
        for(int i=0;i<=n;i++)
        {
    
    
            g[i].clear();
            vis[i]=0;
        }
        for(int i=1;i<=m;i++)
        {
    
    
            int x,y;
            scanf("%d%d",&x,&y);
            if(x==y) continue;
            g[x].push_back(y);
            g[y].push_back(x);
            ans++;
        }
        for(int i=1;i<=n;i++)
        {
    
    
            if(vis[i]==0)
            {
    
    
                int k=dfs(i,0);
                ans=ans+k;
            }
        }
        printf("%d\n",ans);
    }
    //system("pause");
    return 0;
}

Guess you like

Origin blog.csdn.net/Stevenwuxu/article/details/111474050