牛客網Groundhog Looking Dowdy
阿新 • • 發佈:2020-08-08
連結:https://ac.nowcoder.com/acm/contest/5674/F
來源:牛客網
題目描述 :
Groundhog finds that Apple seems to be less intimate than before.He is very distressed for this.After pondering for a long time, Groundhog finds that he looks too dowdy.So, Groundhog decided to improve a little.
Because Groundhog is lazy, he only lists the clothes that can be worn for the nextn{n}n days. On theith{i^{th}}ith day, thejth{j^{th}}jth clothes have a dowdiness ai,ja_{i,j}ai,j.翻譯:
有n天,每天穿一件衣服,第 i 天有 k_i 件衣服可以穿,穿第 j 件衣服的的權值為 a_{i, j} 。
從 n 天中選擇 m 天,求這 m 天中,所穿衣服的權值最大與最小值的最小差是多少。
輸入描述:
The first line contains two integersn{n}n and m{m}m.
Thenn{n}n lines follow,each line contains a integerkik_iki,represents the number of the clothes that can be worn onith{i^{th}}ith day.Thenkik_iki integersai,ja_{i,j}ai,j follow.
輸出描述:
Print in one line the minimum difference.
- 由於要最小化最大值和最小值的差值,因此我們可以把所有衣服按照dowdiness從小到大排個序。
- 排序之後,設最終選出的m件衣服最小覆蓋區間為[L,R],則答案為downdiness[R]-downdiness[L]
- 則一個合法的區間至少需要包含m種不同的日期
- 可以對於每個L求出最小的合法的R,這就轉化為一個簡單的動態視窗問題了。
- 但是由於資料太水,可以求每天的最小全職並求出最小差即可。
正解程式碼:
#include<bits/stdc++.h> using namespace std; struct node { int v; int h; }a[2000010]; bool cmp(node x,node y) { return x.v < y.v; } int m,cnt=0; int vis[2000010]; int main() { int n,k; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { scanf("%d",&k); for(int j=1;j<=k;j++) { cnt++; scanf("%d",&a[cnt].v); a[cnt].h=i; } } sort(a+1,a+1+cnt,cmp); int ans=1e9; int l=1,r=m; int tmp=0; for(int i=l;i<=r;i++) if(!vis[a[i].h]) vis[a[i].h]++;tmp++; while(tmp<m) { r++; if(!vis[a[r].h]) { vis[a[r].h]++; tmp++; } } for(l,r;r<=cnt;) { ans=min(ans,a[r].v-a[l].v); vis[a[l].h]--; l++; if(vis[a[l-1].h]==0) tmp--; while(tmp<m&&r<=cnt) { r++; if(!vis[a[r].h]) { vis[a[r].h]++; tmp++; } } } printf("%d",ans); }View Code
水程式碼:
#include<bits/stdc++.h> using namespace std; int n,m; int l,w; int ans; int a[1000010]; int main() { for (int i=1; i<=1e6; i++) a[i]=1e9+7; ans=1e9+7; scanf("%d%d",&n,&m); for (int i=1; i<=n; i++) { scanf("%d",&l); for (int j=1; j<=l; j++) { scanf("%d",&w); a[i]=min(w,a[i]); } } sort(a+1,a+1+n); for (int i=1; i<=n-m; i++) ans=min(ans,a[i+m-1]-a[i]); printf("%d",ans); }View Code