NC24608. [USACO 2011 Ope S]Learning Languages
描述
输入描述
* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Line i+1 describes the languages that cow i can speak with space-separated integers: , .
输出描述
* Line 1: A single integer that is the minimum number of books that FJ must purchase.
* Lines 2..B+1: Line i+1 contains two space-separated integers: the language id # and the id # of the cow to receive book i. If multiple solutions exist, print any one.
示例1
输入:
3 3 2 3 2 1 2 1 1
输出:
1
C++(g++ 7.5.0) 解法, 执行用时: 29ms, 内存消耗: 512K, 提交时间: 2023-06-22 10:14:47
#include<bits/stdc++.h> using namespace std; int f[(int)1e5]; int lang[(int)1e5]; int find(int x){ return f[x]==x?x:f[x]=find(f[x]); } int main(){ int n,m;int x; cin>>n>>m; for(int i=1;i<=n;i++)f[i]=i;int num; int ans=n-1; for(int i=1;i<=n;i++){ cin>>num; while(num--){ cin>>x; if(lang[x]){ if(find(i)!=find(lang[x])){ f[find(i)]=find(lang[x]); ans--; } } else lang[x]=i; } } cout<<ans; return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 48ms, 内存消耗: 632K, 提交时间: 2020-03-07 13:37:23
#include<bits/stdc++.h> using namespace std; int n,m,f[1000000],nn,x,p[1000000],ans;int find(int x){return f[x]==x?x:f[x]=find(f[x]);}void merge(int x,int y){int fx=find(x),fy=find(y);if(fx!=fy)f[fx]=fy,ans--;} int main(){cin>>n>>m;ans=n;for(int i=1;i<=n;i++)f[i]=i;for(int i=1;i<=n;i++){cin>>nn;for(int j=1;j<=nn;j++){cin>>x;if(p[x])merge(i,p[x]);else p[x]=i;}}cout<<ans-1<<endl; }