TLE30求优化 QAQ
查看原帖
TLE30求优化 QAQ
1318814
wangqiyu_why楼主2025/7/27 10:20
#include <bits/stdc++.h>
using namespace std;
int x, n, m, a[25][25];
void bfs()
 {
    queue<pair<int, int>> q; 
    q.push({0, (1 << n) - 1});
    while(!q.empty())
	 {
        int ans = q.front().first;
        int w1 = q.front().second;
        q.pop();
        if(ans > m)
		 {
            cout << -1 << ' ';
            return;
        }

        if((w1 & (w1 - 1)) == 0) 
		{
            cout << ans << ' ';
            return;
        }
        for(int i = 0; i < m; i++)
		 {
            int c1 = w1;
            for(int j = 0; j < n; j++)
			 {
                if(a[j][i] != a[x][i]) 
				{
                    c1 &= ~(1 << j);
                }
            }
            if(c1 != w1)
			 {
                q.push({ans + 1, c1});
            }
        }
    }
    cout << -1 << ' ';
}

int main() {
    cin >> n >> m;
    for(int i = 0; i < n; i++)
    {
    	for(int j = 0; j < m; j++)
    	{
    		cin >> a[i][j];
		}  
	}
    for(x = 0; x < n; x++) 
    {
    	bfs();
	}  
    return 0;
}
2025/7/27 10:20
加载中...