Assignment 6: Basic Graph Algorithms

本文精选了五道ACM竞赛中的经典算法题目,并详细解析了每道题目的解题思路与实现代码,包括最小生成树的最大边、求双连通分量、A*启发式搜索、Fleury算法求欧拉路径及强连通分量的应用。
  • 1308 Is It A Tree? (1)

  • 1258 Agri-Net (2)

  • 2488 A Knight's Journey (3)

  • 1164 The Castle (3)

  • 2395 Out of Hay (4)

  • 3177 Redundant Paths (4)

  • 1945 Power Hungry Cows (5)

  • 3275 Ranking the Cows (6)

  • 1985 Cow Marathon (7)

  • 2337 Catenyms (7)

  • 2186 Popular Cows (8, challenge problem)

  • 1944 Fiber Communications (8, challenge problem)


    poj2395

    最小生成树的最大边

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    int fa[2010];
    
    struct EDGE {
        int u, v, c;
    
        bool operator<(const EDGE &t)const {
            return c < t.c;
        }
    };
    
    int find(int x) {
        if (x != fa[x])
            fa[x] = find(fa[x]);
        return fa[x];
    }
    
    EDGE edge[10010];
    
    int main() {
        int n, m, a, b, c, i;
        scanf("%d%d", &n, &m);
        for (i = 1; i <= n; ++i)
            fa[i] = i;
        int cnt = 0;
        for (i = 0; i < m; ++i) {
            scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].c);
        }
        sort(edge, edge + m);
        for (i = 0; i < m; ++i) {
            a = find(edge[i].u);
            b = find(edge[i].v);
            if (a != b) {
                ++cnt;
                if (cnt == n - 1)
                    break;
                fa[a] = b;
            }
        }
        printf("%d\n", edge[i].c);
        return 0;
    }

    poj3177

    求双连通分量后缩点,判叶子节点数加一除二。

    #include<cstdio>
    #include<cstring>
    #include<vector>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int d[5010],low[5010];
    bool vis[5010][5010],mat[5010];
    int m,n,tot;
    vector <int> adj[5010];
    void dfs(int u,int p){
        int v;
        mat[u]=1;
        vector <int>::iterator it;
        low[u]=tot++;
        for(it=adj[u].begin();it!=adj[u].end();++it){
            v=*it;
            if(v==p) continue;
            if(!mat[v]) dfs(v,u);
            low[u]=min(low[u],low[v]);
        }
    }
    int main(){
       //  freopen("test.in","r",stdin);
        int i,u,v,ans;
        vector <int>::iterator it;
        while(scanf("%d%d",&n,&m)!=EOF){
            memset(d,0,sizeof(d));
            memset(vis,0,sizeof(vis));
            for(i=1;i<=n;++i) adj[i].clear();
            while(m--){
                scanf("%d%d",&u,&v);
                if(vis[u][v] || vis[v][u]) continue;
                vis[u][v]=1;
                adj[u].push_back(v);
                adj[v].push_back(u);
            }
            tot=0;
            dfs(1,0);
            for(u=1;u<=n;++u){
                for(it=adj[u].begin();it!=adj[u].end();++it){
                    v=*it;
                    if(low[u]!=low[v]){
                        d[low[u]]++;
                    }
                }
            }
            ans=0;
            for(u=0;u<n;++u){
                if(d[u]==1) ans++;
            }
            printf("%d\n",(ans+1)>>1);
        }
        return 0;
    }

    poj1945

    A*启发+广搜+优先队列

    #include<cstdio>
    #include<iostream>
    #include<queue>
    #include<algorithm>
    #include<vector>
    using namespace std;
    #define maxn 80010
    int n;
    
    void swap(int &a,int &b){
        int t=a;
        a=b;
        b=t;
    }
    
    typedef struct S{
        int x,y,s,c;
        S(){}
        S(int xx,int yy,int ss):x(xx),y(yy),s(ss){}
        S(const S& temp){
            x=temp.x,y=temp.y,s=temp.s,c=temp.c;
        }
        bool operator<(const S t)const{
            return c>t.c;
        }
        void out(){
            printf("%d %d %d %d\n",x,y,s,c);
        }
    }NODE;
    NODE now,next;
    priority_queue <NODE> pq;
    
    typedef struct SS{
        int x,y,s;
        SS(){}
        SS(int xx,int yy,int ss):x(xx),y(yy),s(ss){}
    }HASH;
    vector<HASH> hash[maxn];
    
    void cal(NODE &node){
        int temp=n/node.x,cnt=0;
        while(temp){
            ++cnt;
            temp>>=1;
        }
        node.c=node.s+cnt;
    }
    
    bool gaoh(NODE &node){
        int temp;
        temp=node.x+node.y;
       // printf("hash1111=");node.out();
        vector<HASH>::iterator it;
        for(it=hash[temp].begin();it!=hash[temp].end();++it){
            if(it->x==node.x && it->y==node.y){
                if(it->s<=node.s) return 1;
                else {
                    it->s=node.s;
                    return 0;
                }
            }
        }
        hash[temp].push_back(HASH(node.x,node.y,node.s));
       // printf("hash=");node.out();
        return 0;
    }
    
    int gcd(int a,int b){
        for(int t;t=b;b=a%b,a=t);
        return a;
    }
    
    bool gao(NODE &node){
       // node.out();
        if(node.x==n || node.y==n){
            printf("%d\n",node.s);
            return 1;
        }
        if(node.x<node.y) swap(node.x,node.y);
       // printf("temp: "); node.out();
        if(node.x<=0 || node.y<0 || (node.y==0 && node.x>n) || node.x==node.y || (node.x>n && node.y>n) || node.x>=2*n
            || n%gcd(node.x,node.y) || gaoh(node)) return 0;
        cal(node);
        pq.push(node);
        return 0;
    }
    
    int main(){
      //  freopen("aa.in","r",stdin);
      //  freopen("aa.out","w",stdout);
        int i,x,y,s;
        while(scanf("%d",&n)!=EOF){
            while(!pq.empty()) pq.pop();
            for(i=0;i<maxn;++i) hash[i].clear();
            if(n==1){
                printf("0\n");
                continue;
            }
            next=NODE(1,0,0);
            gaoh(next);
            cal(next);
            pq.push(next);
            while(!pq.empty()){
                now=pq.top();
                pq.pop();
                x=now.x,y=now.y,s=now.s+1;
              //  now.out();
                next=NODE(x+x,y,s);if(gao(next)) break;
                next=NODE(x+x,x,s);if(gao(next)) break;
                next=NODE(x+y,y,s);if(gao(next)) break;
                next=NODE(x,x+y,s);if(gao(next)) break;
                next=NODE(x,y+y,s);if(gao(next)) break;
                next=NODE(y+y,y,s);if(gao(next)) break;
                next=NODE(x-y,y,s);if(gao(next)) break;
                next=NODE(x,y-x,s);if(gao(next)) break;
                next=NODE(x,x-y,s);if(gao(next)) break;
                next=NODE(y,y-x,s);if(gao(next)) break;
            }
        }
        return 0;
    }

    poj2337

    Fleury算法求欧拉路

    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    #define maxn 1010
    bool h[30];
    char sstr[maxn][22],*str[maxn];
    int start[maxn],end[maxn];
    int vis[maxn];
    int l[30],r[30];
    int rd[30],cd[30];
    int n,des;
    struct cmp
    {
        bool operator () (const char *a, const char *b)
        {
            return strcmp(a, b)<0;
        }
    };
    int fa[30];
    int find(int x){
        if(x!=fa[x]) fa[x]=find(fa[x]);
        return fa[x];
    }
    int gao(int p,int have){
        if(have==n){
            des=p;
            return 1;
        }
        int i,next=end[p];
        for(i=l[next];i<r[next];++i){
            if(vis[i]==-1){
                vis[i]=p;
                if(gao(i,have+1)) return 1;
                vis[i]=-1;
            }
        }
        return 0;
    }
    int ans[maxn];
    int main(){
       // freopen("test.in","r",stdin);
        int T,i,no,cnt,se;
        scanf("%d",&T);
        while(T--){
            scanf("%d",&n);
            for(i=0;i<26;++i) l[i]=r[i]=rd[i]=cd[i]=0,fa[i]=i;
            for(i=0;i<n;++i){
                scanf("%s",sstr[i]);
                str[i]=sstr[i];
            }
            sort(str,str+n,cmp());
            memset(h,0,sizeof(h));
            for(i=0;i<n;++i){
                start[i]=str[i][0]-'a';
                end[i]=str[i][strlen(str[i])-1]-'a';
                ++cd[start[i]];
                ++rd[end[i]];
                fa[find(start[i])]=find(end[i]);
                h[start[i]]=h[end[i]]=1;
                if(start[i]!=start[i-1]){
                    r[start[i-1]]=i;
                    l[start[i]]=i;
                }
            }
            r[start[i-1]]=i;
        //  for(i=0;i<n;++i) printf("%s\n",str[i]);
            int tot=0;
            for(i=0;i<26;++i)
                if(h[i] && find(i)==i) ++tot;
            if(tot>1){
                printf("***\n");
                continue;
            }
            cnt=0,no=0;
            for(i=0;i<26;++i){
                if(rd[i]-cd[i]>1 || cd[i]-rd[i]>1){
                    no=1;
                    break;
                }
                if(rd[i]-cd[i]==1){
                    ++cnt;
                }
                else if(cd[i]-rd[i]==1){
                    ++cnt;
                    se=i;
                }
            }
          // printf("no=%d cnt=%d\n",no,cnt);
            if(no || cnt>2) {
                printf("***\n");
                continue;
            }
            memset(vis,0xff,sizeof(vis));
            if(!cnt){
                vis[0]=-2;
                gao(0,1);
            } else{
                for(i=l[se];i<r[se];++i){
                    vis[i]=-2;
                    if(gao(i,1)) break;
                    vis[i]=-2;
                }
            }
            cnt=0;
            int Des=des;
           do{
                ans[cnt++]=des;
                des=vis[des];
            } while(des!=-2);
          //  for(i=0;i<cnt;++i) printf("ansi=%d\n",ans[i]);
            for(i=cnt-1;i>0;--i) printf("%s.",str[ans[i]]);
            printf("%s\n",str[ans[i]]);
        }
        return 0;
    }

    poj2186

    求强连通分量后缩点,判唯一的出度为0的点的原始点数

    #include<cstdio>
    #include<cstring>
    #include<stack>
    #include<vector>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    #define maxn 10010
    vector<int> adj[maxn];
    int dfn[maxn],low[maxn],d[maxn],scc[maxn];
    int tot,n,m,cnt;
    stack<int> s;
    void gao(int u){
        int v;
        dfn[u]=low[u]=++tot;
        s.push(u);
        vector<int>::iterator it;
        for(it=adj[u].begin();it!=adj[u].end();++it){
            v=*it;
            if(!dfn[v]) gao(v);
            low[u]=min(low[u],low[v]);
        }
        if(low[u]==dfn[u]){
            ++cnt;
            while(!s.empty()){
                v=s.top();
                scc[v]=cnt;
                s.pop();
                if(low[v]==dfn[v]) break;
            }
        }
    }
    int main(){
        int u,v,i,z=0,ans,p;
        vector<int>::iterator it;
        scanf("%d%d",&n,&m);
        while(m--){
            scanf("%d%d",&u,&v);
            adj[u].push_back(v);
        }
        for(i=1;i<=n;++i)
            if(!dfn[i]) gao(i);
        for(i=1;i<=n;++i){
            for(it=adj[i].begin();it!=adj[i].end();++it){
                if(scc[i]!=scc[*it]) ++d[scc[i]];
            }
        }
        for(i=1;i<=cnt;++i)
            if(!d[i]) ++z,p=i;
        if(z>1 || !z) printf("0\n");
        else{
            ans=0;
            for(i=1;i<=n;++i)
                if(scc[i]==p) ++ans;
            printf("%d\n",ans);
        }
        return 0;
    }

    poj1944

    枚举弃边,跳表统计数量

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    #define maxn 1010
    #define maxp 10010
    int n,p;
    int x[maxp],y[maxp];
    int f[maxn];
    void swap(int &a,int &b){
        int t=a;
        a=b;
        b=t;
    }
    int main(){
        int i,ans,j,temp,far;
        scanf("%d%d",&n,&p);
        ans=n;
        for(i=0;i<p;++i){
            scanf("%d%d",&x[i],&y[i]);
            if(x[i]==y[i]){
                --i,--p;
            }else if(x[i]>y[i]){
                swap(x[i],y[i]);
            }
        }
        for(i=1;i<=n;++i){
            memset(f,0,sizeof(f));
            for(j=0;j<p;++j){
                if(x[j]>=i+1 || y[j]<=i){
                    f[x[j]]=max(y[j],f[x[j]]);
                }else{
                    f[y[j]]=n+1;
                    f[1]=max(x[j],f[1]);
                }
            }
            temp=0;
            far=1;
            for(j=1;j<=n;++j){
                if(f[j]>far){
                    temp+=f[j]-max(far,j);
                    far=f[j];
                }
            }
            ans=min(temp,ans);
        }
        printf("%d\n",ans);
        return 0;
    }


Write a C program that can be run in the Microsoft Visual Studio to partitions a hypergraph G = (V, E) into 2 partitions. The Assignment Write a computer program that takes a netlist represented by a weighted hypergraph and partitions it into two partitions. Each node is associated with an area value and each edge has an edge cost. Your program should minimize the total cost of the cut set, while satisfying the area constraint that the total area of partition 1 should satisfy the balance criteria as described in the class. That is, if the area sum of all the nodes is A, then the area of partition 1 should be greater than or equal to ra-tio_factor *A – amax and less than or equal to ratio_factor *A + amax, where amax is the maximum value among all cell areas. The program should prompt the user for the value of ratio_factor. Assumptions and Requirements of the Implementation 1. Your program should not have any limitation on the maximum number of nodes and the edges of the hypergraph. Each hyperedge could connect any subset of nodes in the hypergraph. 2. Each node area is a non-negative integer, and each edge cost is a non-negative floating- point value. 3. All the ids are 0-based. Namely, the id of the first element is 0, instead of 1. 4. The output of each partition should include the list of node ids, sorted in the ascending order. 5. The partition with the smaller minimum node id is listed first in the output. 6. Use balance criteria as the tiebreaker when there are multiple cell moves giving the max-imum gain, as described in the class. 7. Use the input and output formats given in the Sample Test Cases section. Sample Test Cases Test1: Please enter the number of nodes: 4 Please enter each of the 4 nodes with its id and the node area: 0 1 1 1 2 1 3 1 Please enter the number of edges: 3 Please enter each of the 3 edges with the number of connected nodes and their node ids, followed by the edge cost: 2 0 1 1 2 1 2 3 2 2 3 1 Please enter the percentage of the ratio factor: 50 The node ids of the partition 0 are 0 The node ids of the partition 1 are 1, 2, 3 The total cut cost is 1 Test2: Please enter the number of nodes: 4 Please enter each of the 4 nodes with its id and the node area: 0 1 1 4 2 2 3 1 Please enter the number of edges: 3 Please enter each of the 3 edges with the number of connected nodes and their node ids, followed by the edge cost: 3 0 1 2 5 3 0 2 3 3 3 0 1 3 4 Please enter the percentage of ratio factor: 50 The node ids of the partition 0 are 3 The node ids of the partition 1 are 0, 1, 2 The total cut cost is 7
07-08
Hypergraph partitioning is a complex combinatorial optimization problem that finds applications in various domains, including VLSI design, parallel computing, and data clustering. The goal of hypergraph partitioning is to divide the nodes into multiple partitions such that the total cost of the cut hyperedges (those connecting nodes in different partitions) is minimized while satisfying area constraints on each partition. ### Problem Overview The specific task involves: - Partitioning a hypergraph into two disjoint sets. - Minimizing the cut cost, which is the sum of weights of hyperedges crossing between the partitions. - Ensuring that the total area (or weight) in each partition satisfies given constraints. This problem is NP-hard, so practical implementations often rely on heuristic or metaheuristic algorithms like Kernighan-Lin algorithm, simulated annealing, or multilevel partitioning frameworks. ### Implementation Steps To implement this in **C using Microsoft Visual Studio**, the following steps can be followed: #### 1. Data Structures Define appropriate data structures for representing the hypergraph, including: - Nodes with area constraints. - Hyperedges connecting multiple nodes. - Weights associated with nodes and hyperedges. ```c typedef struct { int id; int area; // Area of the node } Node; typedef struct { int *nodes; // List of connected node indices int num_nodes; int weight; // Weight of the hyperedge } HyperEdge; typedef struct { Node *nodes; HyperEdge *edges; int num_nodes; int num_edges; } HyperGraph; ``` #### 2. Objective Function Implement a function to calculate the cut cost based on the current partition assignment. ```c int calculate_cut_cost(HyperGraph *hg, int *partition) { int cut_cost = 0; for (int i = 0; i < hg->num_edges; i++) { HyperEdge edge = hg->edges[i]; int part_flag[2] = {0}; // Tracks if nodes from both partitions are present for (int j = 0; j < edge.num_nodes; j++) { int node_id = edge.nodes[j]; part_flag[partition[node_id]] = 1; } if (part_flag[0] && part_flag[1]) { cut_cost += edge.weight; } } return cut_cost; } ``` #### 3. Area Constraint Check Ensure that the area in each partition does not exceed the specified limit. ```c int check_area_constraints(HyperGraph *hg, int *partition, int max_area_p0, int max_area_p1) { int area_p0 = 0, area_p1 = 0; for (int i = 0; i < hg->num_nodes; i++) { if (partition[i] == 0) area_p0 += hg->nodes[i].area; else area_p1 += hg->nodes[i].area; } return (area_p0 <= max_area_p0 && area_p1 <= max_area_p1); } ``` #### 4. Partitioning Algorithm Use a heuristic approach such as greedy assignment or local search to iteratively improve the partitioning. A basic greedy method could be implemented as follows: ```c void greedy_partition(HyperGraph *hg, int *partition, int max_area_p0, int max_area_p1) { for (int i = 0; i < hg->num_nodes; i++) { partition[i] = 0; // Initial assignment to partition 0 } // Adjustments to balance area constraints int area_p0 = 0, area_p1 = 0; for (int i = 0; i < hg->num_nodes; i++) { area_p0 += hg->nodes[i].area; } for (int i = 0; i < hg->num_nodes; i++) { int node_area = hg->nodes[i].area; if (area_p0 - node_area <= max_area_p0 && area_p1 + node_area <= max_area_p1) { partition[i] = 1; area_p0 -= node_area; area_p1 += node_area; } } } ``` #### 5. Main Execution Flow Incorporate all components within the main function and test with sample input data. ```c int main() { // Initialize hypergraph with sample data HyperGraph hg; hg.num_nodes = 4; hg.nodes = malloc(hg.num_nodes * sizeof(Node)); hg.nodes[0].id = 0; hg.nodes[0].area = 10; hg.nodes[1].id = 1; hg.nodes[1].area = 20; hg.nodes[2].id = 2; hg.nodes[2].area = 15; hg.nodes[3].id = 3; hg.nodes[3].area = 5; hg.num_edges = 2; hg.edges = malloc(hg.num_edges * sizeof(HyperEdge)); hg.edges[0].nodes = (int[]){0, 1, 2}; hg.edges[0].num_nodes = 3; hg.edges[0].weight = 5; hg.edges[1].nodes = (int[]){2, 3}; hg.edges[1].num_nodes = 2; hg.edges[1].weight = 3; int *partition = malloc(hg.num_nodes * sizeof(int)); int max_area_p0 = 30, max_area_p1 = 30; greedy_partition(&hg, partition, max_area_p0, max_area_p1); printf("Partition assignments: "); for (int i = 0; i < hg.num_nodes; i++) { printf("%d ", partition[i]); } printf("\nCut Cost: %d\n", calculate_cut_cost(&hg, partition)); free(hg.nodes); free(hg.edges); free(partition); return 0; } ``` ### Notes on Optimization and Extensions - **Multilevel Framework**: Implement a coarsening phase where the graph is simplified before partitioning, followed by refinement at each level. - **Kernighan-Lin Algorithm**: For better results, use iterative improvement techniques to swap nodes between partitions to reduce the cut cost while maintaining area constraints. - **Parallelization**: Consider using multi-threading or GPU acceleration for large-scale hypergraphs.
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值