题目链接:
https://code.google.com/codejam/contest/204113/dashboard
题意:
题解:
我们只关心每一行最后一个1的位置。
考虑第i行应该放什么,就是a[j]<=i的都行,要交换次数最少,就找到离i最近的一行,然后累计答案。
代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 #define MS(a) memset(a,0,sizeof(a)) 5 #define MP make_pair 6 #define PB push_back 7 const int INF = 0x3f3f3f3f; 8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL; 9 inline ll read(){ 10 ll x=0,f=1;char ch=getchar(); 11 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 12 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 13 return x*f; 14 } 15 ////////////////////////////////////////////////////////////////////////// 16 const int maxn = 1e5+10; 17 18 int a[50]; 19 20 int main(){ 21 freopen("2.7.2_A-large-practice.in","r",stdin); 22 freopen("2.7.2_A-large-practice.out","w",stdout); 23 int T=read(); 24 for(int cas=1; cas<=T; cas++){ 25 int n = read(); char ch; 26 for(int i=0; i<n; i++){ 27 a[i] = -1; 28 for(int j=0; j<n; j++){ 29 scanf(" %c",&ch); 30 if(ch=='1') a[i]=j; 31 } 32 } 33 34 int res = 0, pos; 35 for(int i=0; i<n; i++){ 36 for(int j=i; j<n; j++){ 37 if(a[j] <= i){ 38 pos = j; 39 break; 40 } 41 } 42 43 for(int k=pos; k>i; k--){ 44 swap(a[k],a[k-1]); 45 res++; 46 } 47 } 48 cout << "Case #" << cas << ": " << res << endl; 49 } 50 51 return 0; 52 }