【2018年全國多校算法寒假訓練營練習比賽(第四場)-A】石油采集(匈牙利算法)
阿新 • • 發佈:2018-02-14
sca scanf tor 代碼 contest bit span 比賽 targe
試題鏈接:https://www.nowcoder.com/acm/contest/76/A
【思路】
每個‘#’的右邊和下邊如果也是‘#’說明這兩個點構成通路,以此重構一幅圖,然後找二分圖的最大匹配。
【代碼】
#include<bits/stdc++.h> using namespace std; char mp[55][55]; bool vis[2505]; vector<int>G[2505]; int mp1[55][55], match[2505], n; bool dfs(int u) {for(int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if(!vis[v]) { vis[v] = 1; if(match[v] == -1 || dfs(match[v])) { match[v] = u; return 1; } } } return 0; }int main() { int t, cas = 0; cin>>t; while(t--) { int num = 0; scanf("%d", &n); for(int i = 0; i < n; i++) scanf("%s", mp[i]); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) if(mp[i][j] == ‘#‘) mp1[i][j] = ++num; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { if(mp[i][j] == ‘#‘) { if(mp[i+1][j] == ‘#‘) G[mp1[i][j]].push_back(mp1[i+1][j]), G[mp1[i+1][j]].push_back(mp1[i][j]); if(mp[i][j+1] == ‘#‘) G[mp1[i][j]].push_back(mp1[i][j+1]), G[mp1[i][j+1]].push_back(mp1[i][j]); } } memset(match, -1, sizeof match); int ans = 0; for(int i = 1; i <= num; i++) { memset(vis, 0, sizeof vis); if(dfs(i)) ans++; } printf("Case %d: %d\n", ++cas, ans/2); } return 0; }
【2018年全國多校算法寒假訓練營練習比賽(第四場)-A】石油采集(匈牙利算法)