萌新求助 TLE 2,8,10
查看原帖
萌新求助 TLE 2,8,10
115353
magicat楼主2022/8/13 15:22

大力BFS染色,调了一晚上不知道为什么TLE了,救救孩子

代码如下:


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#include <map>

using namespace std;
#define fi first
#define se second
#define pb push_back
#define endl '\n'

typedef long long LL;
unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<long long,long long> PLL;


   
int n,k,r;
int op[110][110][5];
int dx[]={0,0,0,-1,1};
int dy[]={0,-1,1,0,0};// 西东南北
vector<PII> cow;        //牛坐标
vector<int> donate;     //连通块贡献
bool vis[110][110];      //染色标记
map<PII,int> mp;        //牛坐标
int init(int r1,int c1,int r2, int c2)
{
    for(int i=1;i<=4;i++)
        if(r1+dx[i]==r2&&c1+dy[i]==c2)
            return i;
}
void bfs()
{
    for(int i=0;i<k;i++)
    {
        if(vis[cow[i].fi][cow[i].se]==false&&mp[cow[i]]==1)
        {
            int cnt=0;
            queue<PII> q;   
            q.push({cow[i].fi,cow[i].se});
            vis[cow[i].fi][cow[i].se]=true;
            while(!q.empty())
            {
                auto t=q.front();   q.pop();
                int x=t.fi,y=t.se;
                vis[x][y]=true;
                if(mp[{x,y}]==1) 
                    cnt++,mp[{x,y}]=0;
            
                for(int j=1;j<=4;j++)
                {
                    if(op[x][y][j]==1)
                    {
                        int tx=x+dx[j];
                        int ty=y+dy[j];
                        if(tx<=0||tx>n||ty<=0||ty>n||vis[tx][ty]==true)    continue;
                        q.push({tx,ty});
                    }
                }
            }
            donate.pb(cnt);
        }
    }
}

int main()
{
    std::ios::sync_with_stdio(false);   cin.tie(nullptr), cout.tie(nullptr);
    cin>>n>>k>>r;
    //初始化边
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            for(int k=1;k<=4;k++)
                op[i][j][k]=1;
    
    for(int i=1;i<=r;i++)
    {
        int r1,c1,r2,c2;    
        cin>>r1>>c1>>r2>>c2;
        op[r1][c1][init(r1,c1,r2,c2)]=0;
        op[r2][c2][init(r2,c2,r1,c1)]=0;
        //删边
    }

    for(int i=1;i<=k;i++)
    {
        int x,y;    cin>>x>>y;    cow.pb({x,y});
        mp[{x,y}]=1;
    }
    bfs();
    LL ans=0;
    int len=donate.size();
    for(int i=0;i<len;i++)
        for(int j=i+1;j<len;j++)
            ans+=donate[i]*donate[j];
    cout<<ans<<endl;
    return 0;
}
2022/8/13 15:22
加载中...